Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between newLine() and carriage return("\r")

Tags:

java

What is the difference between newLine() and carriage return ("\r")? Which one is best to use?

File f = new File(strFileGenLoc);
BufferedWriter bw = new BufferedWriter(new FileWriter(f, false));
rs = stmt.executeQuery("select * from jpdata");
while ( rs.next() ) 
{
    bw.write(rs.getString(1)==null? "":rs.getString(1));
    bw.newLine();
}
like image 315
Manu Avatar asked Nov 29 '22 11:11

Manu


2 Answers

In the old days of ASR-33 teletypes (and, later, dot-matrix printers with travelling print-heads), the CR literally returned the carriage to the left, as in a typewriter, and the LF advanced the paper. The machinery could overlap the operations if the CR came before the LF, so that's why the newline character was always CR-LF, i.e. \r\n. If you got it back to front it took much longer to print. Unix was the first (only?) system to adopt just \n as the standard line separator. DOS/Windows didn't.

like image 39
user207421 Avatar answered Dec 05 '22 15:12

user207421


Assuming you mean this:

public static String newLine = System.getProperty("line.separator");

newLine is environment agnostic \r isn't.

So newLine will give you \r\n on windows but \n on another environment.

However, you shouldn't use this in a JTextArea and println will work fine with just \n on windows.

Edit now that I've seen the code and your comment

In your situation. I think you should use your own constant - \r\n

  File f = new File(strFileGenLoc);
  BufferedWriter bw = new BufferedWriter(new FileWriter(f, false));
  rs = stmt.executeQuery("select * from jpdata");
  while ( rs.next() ) {
    bw.write(rs.getString(1)==null? "":rs.getString(1));
    bw.write("\\r\\n");
  }
like image 158
Rob Stevenson-Leggett Avatar answered Dec 05 '22 16:12

Rob Stevenson-Leggett