我从另一个问题中找到了这段代码
private void updateLine(String toUpdate, String updated) throws IOException {
BufferedReader file = new BufferedReader(new FileReader(data));
String line;
String input = "";
while ((line = file.readLine()) != null)
input += line + "\n";
input = input.replace(toUpdate, updated);
FileOutputStream os = new FileOutputStream(data);
os.write(input.getBytes());
file.close();
os.close();
}
这是我替换某些行之前的文件
example1
example2
example3
但是当我替换一行时,文件现在看起来像这样
example1example2example3
当文件中有很多行时,这使得无法读取文件。
我将如何编辑上面的代码以使我的文件看起来像开始时的样子?
Use System.lineSeparator()代替\n
.
while ((line = file.readLine()) != null)
input += line + System.lineSeparator();
问题是在 Unix 系统上,行分隔符是\n
而在 Windows 系统上,它是\r\n
.
在 Java 7 之前的 Java 版本中,您必须使用System.getProperty("line.separator")
反而。
正如评论中指出的,如果您担心内存使用情况,明智的做法是不要将整个输出存储在变量中,而是在用于处理输入的循环中逐行写出它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)