001: /*
002:
003: Derby - Class org.apache.derby.iapi.services.io.NewByteArrayInputStream
004:
005: Licensed to the Apache Software Foundation (ASF) under one or more
006: contributor license agreements. See the NOTICE file distributed with
007: this work for additional information regarding copyright ownership.
008: The ASF licenses this file to you under the Apache License, Version 2.0
009: (the "License"); you may not use this file except in compliance with
010: the License. You may obtain a copy of the License at
011:
012: http://www.apache.org/licenses/LICENSE-2.0
013:
014: Unless required by applicable law or agreed to in writing, software
015: distributed under the License is distributed on an "AS IS" BASIS,
016: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
017: See the License for the specific language governing permissions and
018: limitations under the License.
019:
020: */
021:
022: package org.apache.derby.iapi.services.io;
023:
024: import java.io.InputStream;
025: import java.io.IOException;
026:
027: /**
028: An InputStream that is like java.io.ByteArrayInputStream but supports
029: a close() call that causes all methods to throw an IOException.
030: Java's ByteInputStream has a close() method that does not do anything.
031: */
032: public final class NewByteArrayInputStream extends InputStream {
033:
034: private byte[] data;
035: private int offset;
036: private int length;
037:
038: public NewByteArrayInputStream(byte[] data) {
039: this (data, 0, data.length);
040: }
041:
042: public NewByteArrayInputStream(byte[] data, int offset, int length) {
043: this .data = data;
044: this .offset = offset;
045: this .length = length;
046: }
047:
048: /*
049: ** Public methods
050: */
051: public int read() throws IOException {
052: if (data == null)
053: throw new IOException();
054:
055: if (length == 0)
056: return -1; // end of file
057:
058: length--;
059:
060: return data[offset++] & 0xff;
061:
062: }
063:
064: public int read(byte b[], int off, int len) throws IOException {
065: if (data == null)
066: throw new IOException();
067:
068: if (length == 0)
069: return -1;
070:
071: if (len > length)
072: len = length;
073:
074: System.arraycopy(data, offset, b, off, len);
075: offset += len;
076: length -= len;
077: return len;
078: }
079:
080: public long skip(long count) throws IOException {
081: if (data == null)
082: throw new IOException();
083:
084: if (length == 0)
085: return -1;
086:
087: if (count > length)
088: count = length;
089:
090: offset += (int) count;
091: length -= (int) count;
092:
093: return count;
094:
095: }
096:
097: public int available() throws IOException {
098: if (data == null)
099: throw new IOException();
100:
101: return length;
102: }
103:
104: public byte[] getData() {
105: return data;
106: }
107:
108: public void close() {
109: data = null;
110: }
111:
112: }
|