Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CRLF into java string

Tags:

java

string

I've coded a string in Java where I inserted a LF (linefeed) at the end like this:

String str = "......\n"; 

Now I need to need newline made of a Carriage Return and a Line Feed, a CRLF. In hex that is 0D 0A instead of 0A. Is there a way to insert this into my string?

like image 492
Claudio Pomo Avatar asked Dec 11 '12 13:12

Claudio Pomo


People also ask

What does \r do in Java?

'\r' is the representation of the special character CR (carriage return), it moves the cursor to the beginning of the line. '\n'(line feed) moves the cursor to the next line . On windows both are combined as \r\n to indicate an end of line (ie, move the cursor to the beginning of the next line).

What is %s in Java?

the %s is a 'format character', indicating "insert a string here". The extra parameters after the string in your two function calls are the values to fill into the format character placeholders: In the first example, %s will be replaced with the contents of the command variable.

How do you escape a new line in Java?

Java code for the escape sequence \n : // This \n escape sequence is for a new line.


2 Answers

Use \r\n:

String str = "......\r\n"; 

From the JLS:

\n    /* \u000a: linefeed LF */ \r    /* \u000d: carriage return CR */ 
like image 110
NPE Avatar answered Sep 30 '22 12:09

NPE


Perhaps the simplest way is to use constant strings. I've taken this from my own ASCII class which defines all 33 non printable codes as their ASCII name, e.g.

public final static char CR  = (char) 0x0D; public final static char LF  = (char) 0x0A;   public final static String CRLF  = "" + CR + LF;     // "" forces conversion to string  String twoLines = "Line1" + CRLF + "Line2";   // 12 characters 
like image 40
user1459519 Avatar answered Sep 30 '22 12:09

user1459519