Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Carriage return and new line with Java and readLine()

Tags:

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

like image 711
Joel Avatar asked Jan 21 '11 11:01

Joel


People also ask

Does BufferedReader readLine include newline?

BufferedReader The readLine() method reads a line of text from the file and returns a string containing the contents of the line, excluding any line-termination characters or null.

How do you return a new line in Java?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

Is \n line feed or carriage return?

A line feed means moving one line forward. The code is \n . A carriage return means moving the cursor to the beginning of the line. The code is \r .

What is the difference between carriage return and new line JAVA?

They are just numbers. Typically, however, a newline character implies a line feed and a carriage return when sent to an character output device. Carriage return strictly means return to the left margin. It's from a device that was used in the early part of the last century.


1 Answers

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().

like image 156
aioobe Avatar answered Sep 21 '22 15:09

aioobe