简体   繁体   English

Java流阅读器一直阻塞到流结束

[英]Java stream reader blocks until end-of-stream

Basically, I have written myself some InputStream (for further use as System.in), which accepts and consumes buffer loaded by Swing components. 基本上,我为自己编写了一些InputStream(供System.in进一步使用),它接受和使用Swing组件加载的缓冲区。

NOTE: Print statements were inserted for debugging purposes. 注意:插入打印语句是为了进行调试。

The read() method: 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;
}

Reading raw bytes from stream WORKS: 从流WORKS读取原始字节:

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

Output: 输出:

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

The 0x a is the NL character (Yeah I am on Unix like system) 0x a是NL字符(是的,我在Unix之类的系统上)

It outputs consumed characters as the stream is supplied additional data, and blocks while not. 当向流提供附加数据时,它将输出消耗的字符,而在不输出时阻塞。

But this does NOT work: 但这不起作用:

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

This approach simply consumes all the available data in the input stream, and blocks until the end of stream ( read() returning -1 ) has been reached. 此方法仅消耗输入流中的所有可用数据,并阻塞直到流的末尾(read()返回-1)为止。 Either it seems to completely ignore the NL character in the stream, or the NL is inserted into the buffer wrong way (I highly doubt it is the latter) 似乎完全忽略了流中的NL字符,或者将NL以错误的方式插入到缓冲区中(我非常怀疑是后者)

What do you think is the cause if the issue? 如果出现问题,您认为是什么原因?

k5_ has already pointed out the answer in his comment: k5_已经在他的评论中指出了答案:

Scanner doesnt use read() method. 扫描仪不使用read()方法。 It uses read(byte[]) , did you override that? 它使用read(byte[]) ,您重写了吗?

But didn't rewrite it as answer so I did. 但是我没有重写它作为答案。 All credits to him. 全部归功于他。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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