![](/img/trans.png)
[英]java nio SocketChannel.read does not return -1 to indicate end-of-stream
[英]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;
}
从流WORKS读取原始字节:
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_已经在他的评论中指出了答案:
扫描仪不使用
read()
方法。 它使用read(byte[])
,您重写了吗?
但是我没有重写它作为答案。 全部归功于他。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.