1 | /* |
2 | * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0, |
3 | * and the EPL 1.0 (http://h2database.com/html/license.html). |
4 | * Initial Developer: H2 Group |
5 | */ |
6 | package org.h2.util; |
7 | |
8 | import java.io.IOException; |
9 | 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 | @Override |
36 | public void close() throws IOException { |
37 | if (!closed) { |
38 | in.close(); |
39 | closed = true; |
40 | } |
41 | } |
42 | |
43 | @Override |
44 | public int read(byte[] b, int off, int len) throws IOException { |
45 | return closed ? -1 : autoClose(in.read(b, off, len)); |
46 | } |
47 | |
48 | @Override |
49 | public int read(byte[] b) throws IOException { |
50 | return closed ? -1 : autoClose(in.read(b)); |
51 | } |
52 | |
53 | @Override |
54 | public int read() throws IOException { |
55 | return closed ? -1 : autoClose(in.read()); |
56 | } |
57 | |
58 | } |