[英]Appending a new line to a BufferedWriter
I'm trying to write to a text file with each successive call to writeMore()
writing to a new line if true
is passed as the last argument. 我试图写一个文本文件,并在每次连续调用
writeMore()
写入一个新行,如果将true
作为最后一个参数传递的话。 However, the writer keeps writing to the end of the same first line. 但是,作者继续写到同一第一行的末尾。 I don't understand what the problem is.
我不明白问题是什么。
package FileIO;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Buffered_Writer {
public static void main(String[] args) throws IOException{
String fileName = "myFile.txt";
String message = "I'm written into the file.";
File myFile = new File("C:\\Users\\User\\Desktop\\" + fileName);
try {
myFile.createNewFile();
} catch (Exception e) {
System.out.println("Could not create file!");
}
BufferedWriter writer = new BufferedWriter(new FileWriter(myFile, true));
writer.write(message);
writeMore("This much more has been written.", myFile, true);
writer.close();
}
public static void writeMore(String message, File file, boolean newLine) throws IOException{
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
if (newLine) {
writer.append(" \n");
writer.append(message);
}
else {
writer.append(" " + message);
}
writer.close();
}
}
Why not use the proper method 为什么不使用正确的方法
https://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#newLine() https://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#newLine()
As per the javadocs 根据javadocs
Writes a line separator.
写一个行分隔符。 The line separator string is defined by the system property line.separator, and is not necessarily a single newline ('\\n') character.
行分隔符字符串由系统属性line.separator定义,不一定是单个换行符('\\ n')。
Given 给定
File myFile = new File("C:\\Users\\User\\Desktop\\" + fileName);
I can deduce you are on Windows. 我可以推断出您在Windows上。 The Windows line separator is not
\\n
(it is \\r\\n
but don't hardcode that). Windows行分隔符不是
\\n
(它是\\r\\n
但不要对其进行硬编码)。 Use System.lineSeparator()
instead. 使用
System.lineSeparator()
代替。 Change 更改
writer.append(" \n");
to 至
writer.append(System.lineSeparator());
The best solution is to use BufferedWriter.newLine()
method. 最好的解决方案是使用
BufferedWriter.newLine()
方法。 Additionnaly, do BufferedWriter
should be closed properly (using try with resources
): 另外,应该正确关闭
BufferedWriter
(使用try with resources
):
public static void writeMore(String message, File file, boolean newLine) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, true))) {
if (newLine) {
writer.newLine();
writer.append(message);
} else
writer.append(" ").append(message);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.