从Java中的多个字节数组中逐行读取字符串

时间:2012-11-11 18:32:27

标签: java

我有一个JNI函数“byte [] read()”,它从特定的硬件接口读取一些字节,并在每次调用时返回一个新的字节数组。读取数据始终是ASCII文本数据,并且“\ n”用于行终止。

我想将从函数读取的这些MULTIPLE字节数组转换为InputStream,这样我就可以逐行打印它们。

类似的东西:

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

我该怎么做?

1 个答案:

答案 0 :(得分:2)

您可以选择类java.io.Reader作为基类,重写抽象方法int read( char[] cbuf, int off, int len)以构建自己的面向字符的流。

示例代码:

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

}