Mega Code Archive

 
Categories / Java / File Input Output
 

Creating an input or output stream on a ByteBuffer

import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; public class Main {   public static void main(String[] argv) throws Exception {     ByteBuffer buf = ByteBuffer.allocate(10);     OutputStream os = new ByteBufferBackedOutputStream(buf);     InputStream is = new  ByteBufferBackedInputStream(buf);   } } class ByteBufferBackedInputStream extends InputStream{      ByteBuffer buf;   ByteBufferBackedInputStream( ByteBuffer buf){     this.buf = buf;   }   public synchronized int read() throws IOException {     if (!buf.hasRemaining()) {       return -1;     }     return buf.get();   }   public synchronized int read(byte[] bytes, int off, int len) throws IOException {     len = Math.min(len, buf.remaining());     buf.get(bytes, off, len);     return len;   } } class ByteBufferBackedOutputStream extends OutputStream{   ByteBuffer buf;   ByteBufferBackedOutputStream( ByteBuffer buf){     this.buf = buf;   }   public synchronized void write(int b) throws IOException {     buf.put((byte) b);   }   public synchronized void write(byte[] bytes, int off, int len) throws IOException {     buf.put(bytes, off, len);   }    }