1 | /* |
2 | |
3 | Derby - Class org.apache.derby.iapi.services.io.NewByteArrayInputStream |
4 | |
5 | Copyright 1998, 2004 The Apache Software Foundation or its licensors, as applicable. |
6 | |
7 | Licensed under the Apache License, Version 2.0 (the "License"); |
8 | you may not use this file except in compliance with the License. |
9 | You may obtain a copy of the License at |
10 | |
11 | http://www.apache.org/licenses/LICENSE-2.0 |
12 | |
13 | Unless required by applicable law or agreed to in writing, software |
14 | distributed under the License is distributed on an "AS IS" BASIS, |
15 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
16 | See the License for the specific language governing permissions and |
17 | limitations under the License. |
18 | |
19 | */ |
20 | |
21 | package org.apache.derby.iapi.services.io; |
22 | |
23 | import java.io.InputStream; |
24 | import java.io.IOException; |
25 | |
26 | /** |
27 | An InputStream that is like java.io.ByteArrayInputStream but supports |
28 | a close() call that causes all methods to throw an IOException. |
29 | Java's ByteInputStream has a close() method that does not do anything. |
30 | */ |
31 | public final class NewByteArrayInputStream extends InputStream { |
32 | |
33 | private byte[] data; |
34 | private int offset; |
35 | private int length; |
36 | |
37 | public NewByteArrayInputStream(byte[] data) { |
38 | this(data, 0, data.length); |
39 | } |
40 | |
41 | public NewByteArrayInputStream(byte[] data, int offset, int length) { |
42 | this.data = data; |
43 | this.offset = offset; |
44 | this.length = length; |
45 | } |
46 | |
47 | /* |
48 | ** Public methods |
49 | */ |
50 | public int read() throws IOException { |
51 | if (data == null) |
52 | throw new IOException(); |
53 | |
54 | if (length == 0) |
55 | return -1; // end of file |
56 | |
57 | length--; |
58 | |
59 | return data[offset++] & 0xff ; |
60 | |
61 | } |
62 | |
63 | public int read(byte b[], int off, int len) throws IOException { |
64 | if (data == null) |
65 | throw new IOException(); |
66 | |
67 | if (length == 0) |
68 | return -1; |
69 | |
70 | if (len > length) |
71 | len = length; |
72 | |
73 | System.arraycopy(data, offset, b, off, len); |
74 | offset += len; |
75 | length -= len; |
76 | return len; |
77 | } |
78 | |
79 | public long skip(long count) throws IOException { |
80 | if (data == null) |
81 | throw new IOException(); |
82 | |
83 | if (length == 0) |
84 | return -1; |
85 | |
86 | if (count > length) |
87 | count = length; |
88 | |
89 | offset += (int) count; |
90 | length -= (int) count; |
91 | |
92 | return count; |
93 | |
94 | } |
95 | |
96 | public int available() throws IOException |
97 | { |
98 | if (data == null) |
99 | throw new IOException(); |
100 | |
101 | return length; |
102 | } |
103 | |
104 | public byte[] getData() { return data; } |
105 | |
106 | public void close() |
107 | { |
108 | data = null; |
109 | } |
110 | |
111 | } |