4

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?

Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43
JavaTree
  • 41
  • 1
  • 4
  • what is a "hidden linebreak"? who created this broken file? can you ask her to fix the line break handling? – Timothy Truckle Nov 11 '16 at 09:35
  • 1
    Possible duplicate of [Carriage return and new line with Java and readLine()](http://stackoverflow.com/questions/4758525/carriage-return-and-new-line-with-java-and-readline) – xenteros Nov 11 '16 at 10:34

2 Answers2

4

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;

    }
}
Mats391
  • 1,199
  • 7
  • 12
  • This should be a comment. – xenteros Nov 11 '16 at 09:54
  • Well, I dont have enough reputation to comment yet. You answer wont work as the line should never have \r in it. According to documentation it will consider every \r to terminate a line https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine() – Mats391 Nov 11 '16 at 10:04
  • you should've used `StringBuilder`, otherwise your code would be awfully slow for big strings. – Dan M. Nov 13 '17 at 13:30
  • Also, it loops indefinitely because `c = reader.read()` is missing. – Dan M. Nov 13 '17 at 16:14
2

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