JavaTree
JavaTree

Reputation: 41

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?

Upvotes: 4

Views: 4118

Answers (2)

Cleverson Pohlod
Cleverson Pohlod

Reputation: 21

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

Upvotes: 2

Mats391
Mats391

Reputation: 1209

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;

    }
}

Upvotes: 4

Related Questions