【问题标题】:Java BufferedWriter - newLine() methodJava BufferedWriter - newLine() 方法
【发布时间】: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


【解决方案1】:

第二个 BufferedWriter,或者更确切地说是第二个隐式 FileWriter,会覆盖第一个创建的文件。

按照您的建议组合语句,或使用附加模式(在这种情况下效率低下)。

【讨论】:

  • 或者,如果您不想合并语句,则可以在整个应用程序中维护对编写器的引用。
  • 由于我的需要,我不能像我所说的那样组合它。我怎样才能附加它?
  • Files.newBufferedWriter(path, charset, StandardOpenOption.APPEND) 第二次。
  • 或者只是按照@IstvanChung 的建议。
猜你喜欢
  • 1970-01-01
  • 2015-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多