Java 流 reader 阻塞直到流结束

Java stream reader blocks until end-of-stream

基本上,我自己编写了一些 InputStream(进一步用作 System.in),它接受并使用由 Swing 组件加载的缓冲区。

注意:插入打印语句是为了调试目的。

read() 方法:

@Override
public int read() {
    System.out.print("[READ] Querying buffer... ");
    while(this.buffer.isEmpty());
    int val = buffer.poll(); // Consumes the first element
    System.out.format("done - 0x%x\n",  val);
    return val;
}

正在从流工作中读取原始字节:

InputStream input = new TestStream();
int chunk = 0;
while(chunk != '\n') {
    chunk = input.read();
    System.out.format("Byte: 0x%x", chunk);
}
input.close();

输出:

[Read] Querying buffer... done - 0x4c
Byte: 0x4c
...
Byte: 0x a

0x a 是 NL 字符(是的,我在类 Unix 系统上)

它在向流提供额外数据时输出消耗的字符,并在没有提供时阻塞。

但这不起作用:

InputStream input = new TestStream();
Scanner scn = new Scanner(input);
System.out.println("Line: " + scn.nextLine());
scn.close();
input.close();

这种方法简单地消耗输入流中的所有可用数据,并阻塞直到到达流的末尾( read() 返回 -1 )。要么似乎完全忽略了流中的 NL 字符,要么 NL 以错误的方式插入缓冲区(我高度怀疑是后者)

如果出现问题,您认为是什么原因造成的?

k5_已经在评论中指出了答案:

Scanner doesnt use read() method. It uses read(byte[]), did you override that?

但我没有将其重写为答案,所以我做了。全部归功于他。