Java StringReader读取超出输入。(Java StringReader reads beyond input. Is this a bug or expected behavior? [

编程入门 行业动态 更新时间:2024-10-16 22:18:16
Java StringReader读取超出输入。(Java StringReader reads beyond input. Is this a bug or expected behavior? [closed])

试试这个代码 -

import java.io.StringReader; public class StringReaderTest { public static void main(String[] args) throws Exception { String sampleString = "abcdefg"; StringReader reader = new StringReader(sampleString); for(int i=0; i<40; i++) { char c = (char) reader.read(); System.out.print(c); } } }

输出是 -

abcdefg?????????????????????????????????

所以读者实际上已经阅读了输入的结尾。 我的印象是,当它试图超越“g”时应该抛出一个例外,但事实并非如此。 它反而返回一个“?” 字符。 这是一个错误还是这种预期的行为?

Try this code -

import java.io.StringReader; public class StringReaderTest { public static void main(String[] args) throws Exception { String sampleString = "abcdefg"; StringReader reader = new StringReader(sampleString); for(int i=0; i<40; i++) { char c = (char) reader.read(); System.out.print(c); } } }

The output is -

abcdefg?????????????????????????????????

So the reader actually read past the end of the input. I was under the impression that it should have thrown an exception when it tried to read beyond "g", but it did not. It instead returned a "?" character. Is this a bug or is this expected behavior?

最满意答案

这种情况下的文档很清楚:

StringReader.read()

返回:读取的字符,如果已到达流的末尾,则返回 -1

The documentation is quite clear in this case:

StringReader.read()

Returns: The character read, or -1 if the end of the stream has been reached

更多推荐

本文发布于:2023-07-15 05:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1110760.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:reads   input   Java   StringReader   behavior

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!