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
更多推荐
发布评论