Sorry if I'm missing something obvious here...but please take a look at this code snippet:
String readString;
String writeString = "O hai world.";
BufferedReader br = new BufferedReader(
new InputStreamReader(
new ByteArrayInputStream(writeString.getBytes()),
"UTF-8"),
1024);
readString = br.readLine();
System.out.println("readString: " + readString);
I'd expect this to print "readString: null" since I thought the BufferedReader would encounter an EOF before detecting a valid EOL, but instead this prints "readString: O hai world". This seems contrary to what the Javadocs for BufferedReader say readLine() will do:
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
I can't see any reason why my string would be re-interpreted to terminate with '\n' and/or '\r'...can someone please illuminate me? Thanks!
EDIT: To provide some context, I'm trying to write JUnit tests to validate a Reader class that I wrote that's designed to read on System.in. Using ByteArrayInputStreams seemed like a reasonable way to simulate System.in (see this relevant SO post).
When my Reader captures a line, it currently relies on BufferedReader.readLine(). For my purposes, my Reader's lines MUST all have been terminated with '\n' or '\r'; encountering EOF without an EOL should not resolve into a valid line. So I guess my question(s) at this point are really as follows (I'll try to test these myself in greater detail when I have time, but hoping you smart folks can help me out):
- Is BufferedReader.readLine() broken/misdocumented? Or is ByteArrayInputStream returning something erroneous when its byte array is exhausted?
- Is this method of testing my Reader erroneous, and should I expect readLine() to function properly when used against System.in? I'm inclined to believe the answer to this is yes.
- Are there better ways to simulate System.in for unit testing?
- If I need to strictly discriminate against '\n' and '\r' when reading from an InputStream, am I better off writing my own readLine() method? I'd be very surprised if this is the case.
Thanks again!