01: /*
02: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
03: * (http://h2database.com/html/license.html).
04: * Initial Developer: H2 Group
05: */
06: package org.h2.util;
07:
08: import java.io.IOException;
09: import java.io.InputStream;
10:
11: /**
12: * This input stream wrapper closes the base input stream when fully read.
13: */
14: public class AutoCloseInputStream extends InputStream {
15:
16: private final InputStream in;
17: private boolean closed;
18:
19: /**
20: * Create a new input stream.
21: *
22: * @param in the input stream
23: */
24: public AutoCloseInputStream(InputStream in) {
25: this .in = in;
26: }
27:
28: private int autoClose(int x) throws IOException {
29: if (x < 0) {
30: close();
31: }
32: return x;
33: }
34:
35: public void close() throws IOException {
36: if (!closed) {
37: in.close();
38: closed = true;
39: }
40: }
41:
42: public int read(byte[] b, int off, int len) throws IOException {
43: return closed ? -1 : autoClose(in.read(b, off, len));
44: }
45:
46: public int read(byte[] b) throws IOException {
47: return closed ? -1 : autoClose(in.read(b));
48: }
49:
50: public int read() throws IOException {
51: return closed ? -1 : autoClose(in.read());
52: }
53:
54: }
|