26

I am using the following code to establish a HTTP connection and read data:

con = (HttpURLConnection) new URL("http://stream.twitter.com/1/statuses/sample.json").openConnection();
...
con.connect();
while (line = rd.readLine()) {
    if (line.contains("\r\n")) {
      System.out.println("Carriage return + new line");
    }
} 

However, it seems like "\r\n" is not part of the string (line), although the server does return them. How can I read the data and detect "\r\n"?

Thanks,

Joel

Joel
  • 5,949
  • 12
  • 42
  • 58
  • 3
    `while (line = rd.readLine())` won't even compile. Also, what's the type of `rd` and how do you get hold of it? – aioobe Jan 21 '11 at 11:59
  • 1
    I assume you are using `BufferedReader` with `rd`, when you read with `readLine()`, `\n` and `\r` chars will be trimmed from the result, you can not see them if you use this method. You should consider using `read()`. – ahmet alp balkan Jan 21 '11 at 12:14

3 Answers3

43

If rd is of type BufferedReader there is no way to figure out if readLine() returned something that ended with \n, \r or \r\n... the end-of-line characters are discarded and not part of the returned string.

If you really care about these characters, you can't go through readLine(). You'll have to for instance read the characters one by one through read().

user85421
  • 28,957
  • 10
  • 64
  • 87
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • 46
    I don't like questions / comments starting with "he should not care about that"... he could for instance be sitting with a test-specification that says "look for \r\n uses". It's unlikely, but the point is this: *you don't know*! – aioobe Jan 21 '11 at 12:09
  • 4
    There's nothing wrong with using BufferedReader. Just use character-based methods instead of readLine(). – Sergei Tachenov Jan 21 '11 at 12:37
  • 1
    I suppose you meant `readLine` instead of `getLine` (only found in javax.sound.* for Java SE) – user85421 Jan 21 '11 at 13:20
12

From the javadocs:

public String readLine() throws IOException

Read a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
Throws:
IOException - If an I/O error occurs

Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
I82Much
  • 26,901
  • 13
  • 88
  • 119
  • 5
    But that doesn't solve the issue, how do you get the line terminating characters in the string? – AturSams Jan 15 '15 at 19:27
  • 3
    @JaredBeekman JDK docs are good, but does not include everything. For example from this description it is not clear whether last empty line (as often seen in text editor) is returned as empty string or not considered a line at all. – industryworker3595112 Sep 25 '15 at 10:39
0

In Java, readLine() uses \n and \r as line feed and carriage return end characters to determine the next lines. So, when you use readLine(), then you won't get \n or \r characters to be displayed in the console as these characters will be masked by the readLine(). For more information about readLine(), refer to the official Oracle doc.

To avoid such behavior, we should use read() method from BufferedReader package. The following sample snippet will help to understand how these \n and \r are getting recognized using read().

Let's say you have a file called test_lineFeed.txt which contains line breaks, and if you want to replace them with some defined format like "CR-LF" (CR --> Carriage return, LF --> Line Feed), then use the following snippet.

BufferedReader reader1 = new BufferedReader(
                new InputStreamReader(
                        new FileInputStream("/home/test_lineFeed.txt")
            ));

    int s1 = 0;
    String formattedString = "";
    while ((s1 = reader1.read()) != -1) {

        char character = (char) s1;

        System.out.println("Each Character: "+character+" its hexacode(Ascii): "+Integer.toHexString(character));
        //output : "0a" --> \n 
        //output : "0d" --> \r

        if (character == '\n'){
            formattedString+=" <LF> ";
        }else if (character =='\r'){
            formattedString+=" <CR> ";
        }else
            formattedString+=character;

    }
    System.out.println(formattedString);
Anton Menshov
  • 2,266
  • 14
  • 34
  • 55
Guru
  • 69
  • 5
  • Won't you get an `incomparable types: char and String` error if you compare `character` variable which is `char` with `'\n'` or `'\r'`? – Hmerman6006 Oct 04 '20 at 09:04
  • char character = (char) s1; This is where the type casting is happening. I do not see incomparable types error because of this. – Guru Oct 08 '20 at 11:03