Java 输入流 != 可读
我正在使用 java.util.Scanner 来处理诸如 nextInt() 之类的事情,只要我使用 java.lang.Readable (一个且唯一的构造函数参数),一切都工作正常。但是,当我改为使用 InputStream 时,Scanner.nextInt() 永远不会返回。你知道为什么吗?
我的 InputStream 实现如下所示:
private static class ConsoleInputStream extends InputStream {
...
private byte[] buffer;
private int bufferIndex;
public int read() throws IOException {
...
while (...) {
if (buffer != null && bufferIndex < buffer.length) {
return buffer[bufferIndex++]; // THE COMMENT!
}
...
}
...
}
}
当我通过 THE COMMENT 打印数据时,我(正确地)得到“12\n”的“1”、“2”、“\n”等内容。是否有一些扫描仪连接,我不知道,这导致了这种行为?
I am using java.util.Scanner for things such as nextInt(), and all was working fine as long as I was using a java.lang.Readable (one and only constructor argument). However, when I changed to using an InputStream instead, Scanner.nextInt() never returns. Do you know why?
My implementation of the InputStream looks like this:
private static class ConsoleInputStream extends InputStream {
...
private byte[] buffer;
private int bufferIndex;
public int read() throws IOException {
...
while (...) {
if (buffer != null && bufferIndex < buffer.length) {
return buffer[bufferIndex++]; // THE COMMENT!
}
...
}
...
}
}
When I print the data by THE COMMENT I (correctly) get stuff like '1','2','\n' for "12\n", etc. Is there some Scanner hookup, unbeknown to me, that cause this behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自 InputStream 的 read() 方法的 javadoc:
“返回:数据的下一个字节,如果到达流末尾,则返回 -1。”
我猜你永远不会返回-1?
From the javadocs for InputStream's read() method:
"Returns: the next byte of data, or -1 if the end of the stream is reached."
I would guess that you're never returning -1?
我认为问题出在你自建的InputStream上。为什么您要构建自己的系统,而不是简单地使用 System.in ?
更新:
好的,明白了。使用 I/O 处理来读取已经可用的字符形式的内容通常没有意义,但我可以看到这将如何让您使用 Scanner 的生活更轻松。
尽管如此,您可能可以通过使用“完成的”InputStream 来为自己节省一些编码和痛苦。我想到的是
Java I/O 很糟糕。很高兴 Sun 的聪明人已经为您封装了大部分内容。
I think the problem is with your self-built InputStream. Why did you build your own, rather than simply simply using System.in ?
Update:
OK, got it. It usually doesn't make sense to use I/O handling to read stuff that's already available, in character form, but I can see how that would make your life easier with Scanner.
Still, you could probably have saved yourself some coding and grief by using a "finished" InputStream. What comes to mind is
Java I/O is yucky. Be glad the bright people from Sun have encapsulated most of it away for you.