Java在文本文件中替换行 [英] Java replace line in a text file
问题描述
private void updateLine(String toUpdate,String updated)throws IOException {
BufferedReader file = new BufferedReader(new FileReader(data));
字符串行;
String input =; ((line = file.readLine())!= null)
输入+ =行+\ n;
input = input.replace(toUpdate,updated);
FileOutputStream os = new FileOutputStream(data);
os.write(input.getBytes());
file.close();
os.close();
这是我的文件,在我换行之前
example1
example2
example3
但是当我换行时,文件现在看起来像这样
example1example2example3
$
如何编辑上面的代码,使我的文件看起来像什么时候开始?
解决方案使用 System.lineSeparator()
而不是 \\\
。
< $($)$($)$($)$($)$
问题是在Unix系统中,行分隔符是 \\\
在Windows系统中,它是
\r\\\
。
版本比Java 7旧,你将不得不使用 System.getProperty(line.separator)
来代替。
正如在注释中指出的那样,如果您对内存使用情况有所顾虑,最好不要将整个输出存储在一个变量中,而是将它逐行写入到用于处理输入。
I found this code from another question
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();
}
This is my file before I replace some lines
example1
example2
example3
But when I replace a line, the file now looks like this
example1example2example3
Which makes it impossible to read the file when there are a lot of lines in it.
How would I go about editing the code above to make my file look what it looked like at the start?
Use System.lineSeparator()
instead of \n
.
while ((line = file.readLine()) != null)
input += line + System.lineSeparator();
The issue is that on Unix systems, the line separator is \n
while on Windows systems, it's \r\n
.
In Java versions older then Java 7, you would have to use System.getProperty("line.separator")
instead.
As pointed out in the comments, if you have concerns about memory usage, it would be wise to not store the entire output in a variable, but write it out line-by-line in the loop that you're using to process the input.
这篇关于Java在文本文件中替换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!