1、将String写入到文件时,换行符有一些会被过滤掉,没有任何效果。


解决办法:

那是因为默认的情况下,界面上的换行时用的"\n",这是LINUX和UNIX的换行符。在windows下换行符是"\r\n".

所以再将String对象写入到文件时,换行符应该把\n写完整成\r\n

例1:

String s = "12443\nkdjf";
//改成String s = "1244\r\nkdjf";      输出结果一样
                                                                    
System.out.print(s);
输出结果是:
12443
kdjf

例2:

String s = "12443\nkdjf";
PrintStream ps = new PrintStream(".\\"+ "testStringNextLine.txt");
 ps.print(s);

在文件testStringNextLine.txt里的显示结果是:

12443kdjf
\n符号直接被忽略

一旦将定义改成如下形式:

String s = "12443\r\nkdjf";   //注意多了\r

显示结果将变成:

12443
kdjf


完整程序:


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;

public class tmptmp {

	/**
	 * @param args
	 */
	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和\r\n都一样,在在控制台输出正常换行
		System.out.print(sb.toString());

		File f = new File(".\\" + "testStringNextLine.txt");
		f.createNewFile();

		File f2 = new File(".\\" + "testStringNextLine2.txt");
		f2.createNewFile();
		try {
			// 无论这里加几个\n,PrintStream输出到文件的换行符都被过滤掉
			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();
		}

	}

}