4

我有一个 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());
}

我怎么做?

4

1 回答 1

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

}
于 2012-11-11T18:44:24.517 回答