在文件中写一个字符串到底是怎么回事

时间:2014-08-19 15:55:51

标签: java string file

如何在文件.txt中写一个字符串到底是怎么回事?

例如,我想写下以下字符串:

  

您好,我是stackoverflow的用户

     

我正在问一个问题

我试过BufferedWriter,PrintWriter,PrintStream,但结果总是一样的,所以在我的文件.txt中,字符串显示如下:

  

您好,我是stackoverflow的用户,我正在问一个问题

有必要分析每个角色还是有更简单的方法?

3 个答案:

答案 0 :(得分:2)

使用任何一个

示例代码:(尝试任何一个)

try (BufferedWriter writer = new BufferedWriter(new FileWriter("abc.txt"))) {
    writer.write("Hello, I'm an user of stackoverflow");
    writer.newLine();
    writer.write("and I'm asking a question");
}

try (PrintWriter writer = new PrintWriter(new FileWriter("abc.txt"))) {
    writer.write("Hello, I'm an user of stackoverflow");
    writer.println();
    writer.write("and I'm asking a question");
}

try (FileWriter writer = new FileWriter("abc.txt")) {
    writer.write("Hello, I'm an user of stackoverflow");
    writer.write(System.lineSeparator());
    writer.write("and I'm asking a question");
}

详细了解Java 7 The try-with-resources Statement以便仔细处理资源。

答案 1 :(得分:2)

问题似乎是换行符。

如果您使用PrintWriter.println(),则会在Windows上使用特定于平台的行分隔符:"\r\n"

Windows Notepad无法处理"\n",但写字板会处理。

答案 2 :(得分:1)

您可以使用BufferedWriter类的newLine()方法。

  

提供了一个newLine()方法,该方法使用平台自己的概念   由系统属性line.separator定义的行分隔符。   并非所有平台都使用换行符('\ n')来终止行。   因此,调用此方法来终止每个输出行   喜欢直接写一个换行符。

您也可以尝试使用\ n:

String s ="Hello, I'm an user of stackoverflow\n"
          +"and I'm asking a question";

String s = String.format("%s\n%s","Hello, I'm an user of stackoverflow",
              "and I'm asking a question");
相关问题