BufferedReader readLine() issue: detecting end of file and empty return lines

后端 未结 5 1346
粉色の甜心
粉色の甜心 2021-01-18 09:14

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

5条回答
  •  清歌不尽
    2021-01-18 10:02

    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();
    }
    

提交回复
热议问题