File D:\maven-qcr-plugin-testsunitaires\qcr4java\h2-1.3.170-sources\target\site\qc\lecode\util\AutoCloseInputStream.java.html

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