简体   繁体   中英

How to skip carriage return as line breaker while reading a file in java

I am reading a text file using BufferedReader.readLine() in java. My text file was created with hidden line breaks. My question is I need to skip carriage return ( \\r ) as line break, only need to consider line feed ( \\n ) as line breaker.

How can I achieve this?

You have to write your own readLine . BufferedReader.readLine will consider all \\r, \\n and \\r\\n as line breaks and you cannot change it. Make a helper where you define your own line breaks.

Edit: could look like this

String readLineIgnoreCR(BufferedReader reader)
{
    int c = reader.read();
    String line = "";
    while(c >= 0)
    {
        if((char) c == '\r')
            continue;
        else if((char) c == '\n')
            return line;
        line += (char) c;

    }
}

Is correct:

    String readLineIgnoreCR(BufferedReader reader) {
        int c = 0;
        String line = "";
        while(c >= 0) {
            c = reader.read();
            if((char) c == '\r')
                continue;
            else if((char) c == '\n')
                return line;
            line += (char) c;
        }
        return line;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM