字符串中的换行符未写入文件
我正在尝试编写一个程序来处理从文件中读入的unicode字符串。 我想到了两种方法 – 一种是我读取包含换行符的整个文件,执行几次正则表达式替换,然后将其写回另一个文件; 另一个我在文件中逐行读取并匹配各行并替换它们并将其写出来的地方。 我无法测试第一种方法,因为字符串中的换行符不会写为文件的换行符。 以下是一些示例代码:
String output = "Hello\nthere!"; BufferedWriter oFile = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("test.txt"), "UTF-16")); System.out.println(output); oFile.write(output); oFile.close();
print语句输出
你好
那里!
但文件内容是
你好!
为什么我的换行不写入文件?
你应该尝试使用
System.getProperty("line.separator")
这是一个未经测试的例子
String output = String.format("Hello%sthere!",System.getProperty("line.separator")); BufferedWriter oFile = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("test.txt"), "UTF-16")); System.out.println(output); oFile.write(output); oFile.close();
我无法测试第一种方法,因为字符串中的换行符不会写为文件的换行符
你确定吗? 你能发布一些显示特定事实的代码吗?
使用System.getProperty(“line.separator”)获取特定于平台的换行符。
考虑使用PrintWriters从例如System.out获取println方法