简体   繁体   中英

Reading line by line strings from multiple byte arrays in Java

I have a JNI function "byte[] read()" which reads some bytes from a particular hardware interface and returns a new byte array each time it is called. The read data is always ASCII text data and has '\\n' for line termination.

I'd like to convert these MULTIPLE byte arrays read from the function into an InputStream so I may print them line by line.

Something like:

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

How do I do that?

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

Sample code:

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();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM