View Javadoc

1   /***
2    * Copyright 2008 ATG DUST Project
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * 
7    * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8    * 
9    * Unless required by applicable law or agreed to in writing, software 
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and limitations under the License.
13   */
14  package atg.test.io;
15  
16  import java.io.IOException;
17  import java.io.InputStream;
18  import java.nio.ByteBuffer;
19  
20  /***
21   * An InputStream which reads from a ByteBuffer
22   * 
23   * @author Adam Belmont
24   * @version $Id:$
25   * @see ByteBuffer
26   * 
27   */
28  public class ByteBufferInputStream extends InputStream {
29  //-------------------------------------
30    /*** Class version string */
31    
32    public static String CLASS_VERSION =
33    "$Id:$";
34    
35    private ByteBuffer mBuffer = null;
36  
37    public ByteBufferInputStream(ByteBuffer pBuffer) {
38      mBuffer = pBuffer;
39    }
40  
41    public int read(byte b[]) throws IOException {
42      return read(b, 0, b.length);
43    }
44  
45    public synchronized int read() throws IOException {
46      if (!mBuffer.hasRemaining()) {
47        return -1;
48      }
49      return mBuffer.get();
50    }
51  
52    public synchronized int read(byte[] bytes, int off, int len)
53        throws IOException {
54      len = Math.min(len, mBuffer.remaining());
55      mBuffer.get(bytes, off, len);
56      return len > 0 ? len : -1;
57    }
58  }