How to write a carraige return to file

Hi!

In my database, I have

“This is line 1
This is line 2.”

I get it out from the database and I want to write it to a file.
In my file, a line break and a carriage return is required. I have tried to convert it like this:


String dbText = rs.getString("text");
char ch = '\
';
dbText = dbText.replaceAll("\\\
", Character.toString(ch) );

But the above code doesn’t work. It still prints out the
instead of having a carriage return and line break.

Please help. Thanks.

have you tried simply printing out the original text? what string do you get? it seems to me you only need to replace \ with \\.

hi rushiku,

Thanks for your reply. But the problem is i don’t get the line break if I do a System.out.println. I get Line1
Line2

Is it because I get it from the database using

String dbText = rs.getString(“text”)

and then I do a

System.out.println(dbText)?

What’s the solution? Please help, thanks.

can you spot your problem from this code ? :slight_smile:

/*
* CharTest is a class to
* test the way escaped sequence codes
* really work.
*/

public class CharTest {
	public static final char nL = '\
';
	public static final String ch = "\
";
	static String dbText1 = "Line1\
Line2";
	static String dbText2 = "Line1\\\
Line2";

	public static void main( String[] args ) {
		System.out.println( "Static Text1: Line1" + nL + "Line2" );
		System.out.println( "Static Text2: Line1" + ch + "Line2" );
		System.out.println( "DB Text1: " + dbText1 );
		System.out.println( "DB Text2: " + dbText2 );
		System.out.println( "Replacement 1: " + dbText1.replaceAll( "Line", "Text" ) );
		System.out.println( "Replacement 2: " + dbText1.replaceAll( "\\\
", ch ) );
		System.out.println( "Replacement 3: " + dbText1.replaceAll( ch, "\\\
" ) );
		System.out.println( "Replacement 4: " + dbText1.replaceAll( Character.toString(nL), "\\\
" ) );
	}
}

Given the following


String test = "foo\
far\\\
bar";
System.out.println( "test 1>" + test + "<" );
char lineReturnChar = 'R';
System.out.println( "test 2>" + test.replace( '\
', lineReturnChar ) + "<" );
String lineReturnString = "\\\\\\\
";
System.out.println( "test 3>" + test.replaceAll( lineReturnString, "boo" ) + "<" );

We get this output:


test 1>foo
far\
bar<
test 2>fooRfar\
bar<
test 3>foo
farboobar<

Test 1 is simply the test string.

Test 2 shows that String.replace will replace the
, but not the \
. This is because slash is the escape character, the second slash has been escaped and is what is actually in memory; hence:
is printed.

Test 3 shows that String.replaceAll will match the \
, given the proper string to look for. Because replaceAll uses regex, we must ‘double escape’: once for Java, again for Regex. So, given the string "\\\
", Java sees "\
" and Regex sees "
", which matches within the supplied test string, which Java provided to Regex as “foo(literal line return char)far
bar”.