Reading rows by rows from multiple byte arrays in Java

I have a JNI function "byte [] read ()" that reads some bytes from a specific hardware interface and returns every new byte every time it is called. Read data is always ASCII text data and has "\ n" to end the line.

I would like to convert these arrays of MULTIPLE arrays read from a function into an InputStream so that I can print them line by line.

Sort of:

while(running) { byte[] in = read(); // Can very well return in complete line SomeInputStream.setMoreIncoming(in); if(SomeInputStream.hasLineData()) System.out.println(SomeInputSream.readline()); } 

How to do it?

+4
source share
1 answer

You can select the java.io.Reader class as the base class, overriding the abstract method int read (char [] cbuf, int off, int len) to create your own character-oriented stream.

Code example:

 import java.io.IOException; import java.io.Reader; public class CustomReader extends Reader { // FIXME: choose a better name native byte[] native_call(); // Your JNI code here @Override public int read( char[] cbuf, int off, int len ) throws IOException { if( this.buffer == null ) { return -1; } final int count = len - off; int remaining = count; do { while( remaining > 0 && this.index < this.buffer.length ) { cbuf[off++] = (char)this.buffer[this.index++]; --remaining; } if( remaining > 0 ) { this.buffer = native_call(); // Your JNI code here this.index = 0; } } while( this.buffer != null && remaining > 0 ); return count - remaining; } @Override public void close() throws IOException { // FIXME: release hardware resources } private int index = 0; private byte[] buffer = native_call(); } 
+2
source

Source: https://habr.com/ru/post/1445378/


All Articles