Java StringReader reads beyond input. Is this a bug or expected behavior? [closed]
-
15-06-2021 - |
Question
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?
Solution
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
OTHER TIPS
According to http://docs.oracle.com/javase/1.4.2/docs/api/java/io/StringReader.html#read%28%29 StringReader.Read() returns -1 if the end of the stream has been reached. It doesn't throw an IOException unless there's some other sort of error.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow