Java language Notes when writing line breaks \ r \ n in a file
2012-03-15 00:39:50| Category: Java | report | font size subscribe to 1, when you write a string to a file, some of the newline characters are filtered out without any effect.
Solution:
So when you write a string object to a file, the line break should be written completely \ r \ n
Example 1:
String s = "12443\NKDJF";
Change to string s = "1244\R\NKDJF"; Same as the output result
System.out.print (s);
The output results are:
12443
Kdjf
Example 2:
String s = "12443\NKDJF";
PrintStream PS = new PrintStream (". \" + "TestStringNextLine.txt");
Ps.print (s);
The results shown in the file TestStringNextLine.txt are:
12443kdjf
\ n symbols are ignored directly
Once the definition is changed to the following form:
String s = "12443\R\NKDJF"; More attention, \ r
The display results will become:
12443
Kdjf
Full program:
public static void Main (string[] args) throws IOException {String s = "Dsfjks" + "n"; System.out.print (s); StringBuffer sb = new StringBuffer ("Sdfkjds"); Sb.append ("\ r \ n"); Sb.append ("2323"); Sb.append ("\ r \ n"); Sb.append ("FJKDSL"); Sb.append ("\ r \ n"); \ n and \ r \ n are the same, in the console output normal line System.out.print (sb.tostring ()); File F = new file (". \" + "TestStringNextLine.txt"); F.createnewfile (); File F2 = new file (". \ \" + "TestStringNextLine2.txt"); F2.createnewfile (); try {//No matter how many \n,printstream output to the file are filtered out printstream PS = new PrintStream (". \" + "TestStringNextLine.txt"); ps.print (Sb.tostring ()); Ps.print ("\ r \ n"); Ps.print ("234"); Ps.print ("\ r \ n"); Ps.close (); FileWriter FW = new FileWriter (F2); BufferedWriter bw = new BufferedWriter (FW); Bw.write (Sb.tostring ()); Bw.write ("\ r \ n"); Bw.write ("\ r \ n"); String s2 = "djfkljw\r\n2323\r\n"; System.out.print (S2); Bw.write (S2); Bw.close (); catch (FileNotFoundException e) {e.printstacktrace ();}}