I want my program to do something when it finds the end of a file (EOF) at the end of the last line of text, and something else when the EOF is at the empty line AFTER that
I tried reading from a BufferedReader that received its input from a socket input stream.
Everything worked fine until the last line, where the readLine()
would just simply hang because the browser wouldn't send a newline terminator on post data.
This is my solution, to be able to read until the end of the input stream.
public String getLine(BufferedReader in)
{
StringBuilder builder = new StringBuilder();
try {
while(in.ready()) {
char input = (char)in.read();
/**
* This method only matches on " \r\n" as a new line indicator.
* change as needed for your own line terminators
*/
if(input == '\r') {
/** If we can read more, read one more character
* If that's a newline, we break and return.
* if not, we add the carriage return and let the
* normal program flow handle the read character
*/
if(in.ready()) {
input = (char)in.read();
if(input == '\n') {
break;
}
else {
builder.append('\r');
}
}
}
builder.append(input);
}
}
catch(IOException ex) {
System.out.println(ex.getMessage());
}
return builder.toString();
}