【发布时间】:2014-05-10 20:35:41
【问题描述】:
我遇到一个问题已经有一段时间了,并且已经测试了我能想到的所有可能性。不幸的是,这些可能性没有奏效。
基本上,我正在尝试使用 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/catch 结合起来,这样就可以了。但这只是一个测试表示;在我的真实代码中,我需要单独执行此操作,以便在触发特定事件时写入 .txt 文件。
基本上,newLine() 方法不会保存,除非我直接在它们后面写文本。
一如既往地感谢任何帮助!
【问题讨论】:
-
您确定问题不在于重新打开文件时会覆盖已经存在的内容吗?
-
您可以使用
Charset charset = StandardCharsets.UTF_8;作为 StandardCharsets 将所有在任何 JRE 中始终可用的字符集作为常量列出(与 ISO-8859-3 不同)。没有 UnsupportedEncodingException!
标签: java file newline bufferedwriter