简体   繁体   English

字符串中的换行符未写入文件

[英]Newlines in string not writing out to file

I'm trying to write a program that manipulates unicode strings read in from a file. 我正在尝试编写一个程序来处理从文件中读入的unicode字符串。 I thought of two approaches - one where I read the whole file containing newlines in, perform a couple regex substitutions, and write it back out to another file; 我想到了两种方法 - 一种是我读取包含换行符的整个文件,执行几次正则表达式替换,然后将其写回另一个文件; the other where I read in the file line by line and match individual lines and substitute on them and write them out. 另一个我在文件中逐行读取并匹配各行并替换它们并将其写出来的地方。 I haven't been able to test the first approach because the newlines in the string are not written as newlines to the file. 我无法测试第一种方法,因为字符串中的换行符不会写为文件的换行符。 Here is some example code to illustrate: 以下是一些示例代码:

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();

The print statement outputs print语句输出

Hello 你好
there! 那里!

but the file contents are 但文件内容是

Hellothere! 你好!

Why aren't my newlines being written to file? 为什么我的换行不写入文件?

You should try using 你应该尝试使用

System.getProperty("line.separator")

Here is an untested example 这是一个未经测试的例子

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();

I haven't been able to test the first approach because the newlines in the string are not written as newlines to the file 我无法测试第一种方法,因为字符串中的换行符不会写为文件的换行符

Are you sure about that? 您确定吗? Could you post some code that shows that specific fact? 你能发布一些显示特定事实的代码吗?

使用System.getProperty(“line.separator”)获取特定于平台的换行符。

考虑使用PrintWriters从例如System.out获取println方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM