4

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?

3
  • Hardware interface provides bytes but you say "line". Lines of text termibated by '\n', in which character encoding? Commented Nov 11, 2012 at 18:38
  • I should have clarified. Only plain ASCII text data is received and lines of text are terminated by '\n'. Commented Nov 11, 2012 at 18:46
  • @sharjeel could you edit your question to clarify also. Commented Nov 11, 2012 at 18:46

1 Answer 1

2

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

}
Sign up to request clarification or add additional context in comments.

2 Comments

Aubin; it is only text. Could you please provider a code snippet?
Thanks. I was hoping that I wouldn't have to write such complex code for seemingly very straightforward problem but I guess I can't escape that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.