Monday 27 June 2022

Implement ByteBuffer input stream

Channels and Buffers are the basic building blocks of Java NIO. Channels are analogous to the streams in IO. All the data should go via channels. If you send any data to channel, the data is placed in a buffer. Any data that is read from a channel is read into a buffer. Buffer is a container that holds some data.

 

Let’s create ByteBufferInputStream by extending InputStream class.

 


ByteBufferInputStream.java

package com.sample.app.streams;

import static java.lang.Math.max;
import static java.lang.Math.min;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

public class ByteBufferInputStream extends InputStream {

	private final ByteBuffer byteBuffer;

	public ByteBufferInputStream(final ByteBuffer byteBuffer) {
		this.byteBuffer = byteBuffer.slice();
	}

	@Override
	public int read() {
		// a & 0xff will give the lowest 8 bits from a. If a is less than 255, it'll
		// return the same number.
		if (byteBuffer.hasRemaining()) {
			return 0xff & byteBuffer.get();
		}

		return -1;
	}

	@Override
	public int read(final byte b[], final int off, final int len) {
		final int minLength = min(len, byteBuffer.remaining());
		byteBuffer.get(b, off, minLength);
		return minLength;
	}

	@Override
	public long skip(long noOfLinesToSkip) {
		final long minLinesToSlip = min(byteBuffer.remaining(), max(noOfLinesToSkip, 0));
		byteBuffer.position((int) (byteBuffer.position() + minLinesToSlip));
		return minLinesToSlip;
	}

	@Override
	public synchronized int available() {
		return byteBuffer.remaining();
	}

	@Override
	public void close() throws IOException {
		// not applicable
	}
}

 

App.java

package com.sample.app;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

import com.sample.app.streams.ByteBufferInputStream;

public class App {

	public static void main(String[] args) throws IOException {
		ByteBuffer byteBuffer = ByteBuffer.allocate(100);
		byteBuffer.put("one\n".getBytes(StandardCharsets.UTF_8));
		byteBuffer.put("two\n".getBytes(StandardCharsets.UTF_8));
		byteBuffer.put("three\n".getBytes(StandardCharsets.UTF_8));
		byteBuffer.put("four\n".getBytes(StandardCharsets.UTF_8));
		byteBuffer.put("five\n".getBytes(StandardCharsets.UTF_8));

		byteBuffer.flip();

		try (ByteBufferInputStream byteBufferInputStream = new ByteBufferInputStream(byteBuffer)) {
			StringBuilder stringBuilder = new StringBuilder();

			int data;
			while ((data = byteBufferInputStream.read()) != -1) {
				stringBuilder.append((char) data);
			}

			System.out.println(stringBuilder.toString());
		}

	}

}

 

Output

one
two
three
four
five

 

 

 

 

  

Previous                                                 Next                                                 Home

No comments:

Post a Comment