gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 21:29:45 27 4
gpt4 key购买 nike

我正在尝试编写一个程序来处理从文件中读入的 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();

打印语句输出

Hello
there!

但是文件内容是

Hellothere!

为什么我的换行符没有写入文件?

最佳答案

你应该尝试使用

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

I haven't been able to test the first approach because the newlines in the string are not written as newlines to the file

你确定吗?您能否发布一些代码来说明这一具体事实?

关于java - 字符串中的换行符未写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1133131/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com