使用 FileWriter 进行基本字符串编辑
Basic String editing with FileWriter
我有 2 个字符串要添加到 txt 文件中。第一个字符串需要在第一行,第二个在第二行。 “\n”命令似乎不起作用,因为在我的输出文件中,两个字符串都在一行中。
FileWriter writer = new FileWriter(measurements);
String text1 = x.measurementToString(x);
String text2 = z.measurementToString(z);
writer.write(text1 + "\n" + text2);
writer.close();
System.out.println("Strings added to file!");
也许您正在 windows 并使用无法将 \n
识别为行分隔符的工具打开文件,例如记事本?
文件 I/O 使用 the Files
class 中的方法更容易。在你的情况下:
Path p = Paths.get("C:/path/to/your/file/filename.ext");
//or
Path p = measurements.toPath();
Files.write(p, Arrays.asList(text1, text2), StandardCharsets.UTF_8);
这将使用您计算机上的默认行分隔符,应该可以解决您的问题。
由于换行符在不同的操作系统中是不同的,您可以使用System.getProperty("line.separator")
来获取操作系统在运行时的换行符。
对于Java7你也可以使用System.lineSeparator()
改用 PrintWriter.println()。
一定是这样的:
try (PrintWriter writer = new PrintWriter(file)) {
writer.println(text1);
writer.println(text2);
}
我有 2 个字符串要添加到 txt 文件中。第一个字符串需要在第一行,第二个在第二行。 “\n”命令似乎不起作用,因为在我的输出文件中,两个字符串都在一行中。
FileWriter writer = new FileWriter(measurements);
String text1 = x.measurementToString(x);
String text2 = z.measurementToString(z);
writer.write(text1 + "\n" + text2);
writer.close();
System.out.println("Strings added to file!");
也许您正在 windows 并使用无法将 \n
识别为行分隔符的工具打开文件,例如记事本?
文件 I/O 使用 the Files
class 中的方法更容易。在你的情况下:
Path p = Paths.get("C:/path/to/your/file/filename.ext");
//or
Path p = measurements.toPath();
Files.write(p, Arrays.asList(text1, text2), StandardCharsets.UTF_8);
这将使用您计算机上的默认行分隔符,应该可以解决您的问题。
由于换行符在不同的操作系统中是不同的,您可以使用System.getProperty("line.separator")
来获取操作系统在运行时的换行符。
对于Java7你也可以使用System.lineSeparator()
改用 PrintWriter.println()。
一定是这样的:
try (PrintWriter writer = new PrintWriter(file)) {
writer.println(text1);
writer.println(text2);
}