[英]Java BufferedWriter - newLine() method
我已经遇到了一段时间,并测试了我能想到的所有可能性。 不幸的是,这些可能性不起作用。
基本上,我试图使用Java中的BufferedWriter写入.txt文件。 我需要此设置,以便可以在每条数据之间插入一行。 想象这是从Java产生的文本文件,它应该看起来像这样:
line1
line2
这是我的代码:
public static void main(String[] args) {
Path path = Paths.get("test.txt");
if (!Files.exists(path)) {
try {
Files.createFile(path);
} catch (IOException e) {
System.out.println("Error in creating test.txt! Read the stacktrace
below.");
e.printStackTrace();
}
}
Charset charset = Charset.forName("UTF-8");
try (BufferedWriter writer = Files.newBufferedWriter(path, charset)) {
String string = "line1";
writer.write(string, 0, string.length());
writer.newLine();
writer.newLine();
writer.flush();
} catch (IOException e) {
System.out.println("Unable to write to file! Read the StackTrace below.");
e.printStackTrace();
}
try (BufferedWriter writer = Files.newBufferedWriter(path, charset)) {
String string = "line2";
writer.write(string, 0, string.length());
writer.flush();
} catch (IOException e) {
System.out.println("Unable to write to file! Read the StackTrace below.");
e.printStackTrace();
}
}
这样的输出将产生一个文本文件,如下所示:
line2
现在,我知道我可以将两个try / catches组合在一起,并且可以正常工作。 但这只是测试的表示; 在我的真实代码中,我需要单独执行此操作,以便每当触发特定事件时就可以在.txt文件中进行写入。
基本上,除非我在它们之后直接编写文本,否则newLine()方法不会保存 。
一如既往地感谢您的帮助!
第二个BufferedWriter或更确切地说第二个隐式FileWriter覆盖第一个创建的文件。
根据您的建议组合语句,或使用追加模式(在这种情况下效率低下)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.