简体   繁体   English

Java BufferedWriter-newLine()方法

[英]Java BufferedWriter - newLine() method

I have been encountering a problem for a while now, and have tested every possibility I can think of. 我已经遇到了一段时间,并测试了我能想到的所有可能性。 Unfortunately, these possibilities did not work. 不幸的是,这些可能性不起作用。

Basically, I am trying to write to a .txt file using BufferedWriter in Java. 基本上,我试图使用Java中的BufferedWriter写入.txt文件。 I need this setup so that I can have a line in between each piece of data. 我需要此设置,以便可以在每条数据之间插入一行。 Imagine this is the text file produced from Java, it should look like this: 想象这是从Java产生的文本文件,它应该看起来像这样:

line1

line2

Here is my code: 这是我的代码:

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();
    }
}

The output of this produces a text file as so: 这样的输出将产生一个文本文件,如下所示:

line2

Now, I know I could just combine my two try/catches, and it would work. 现在,我知道我可以将两个try / catches组合在一起,并且可以正常工作。 But this is just a test representation; 但这只是测试的表示; in my real code, I need to do this separately so I can write in .txt files whenever specific events are triggered. 在我的真实代码中,我需要单独执行此操作,以便每当触发特定事件时就可以在.txt文件中进行写入。

Basically, the newLine() methods are not saving unless I write text directly after them. 基本上,除非我在它们之后直接编写文本,否则newLine()方法不会保存

Any help is appreciated, as always! 一如既往地感谢您的帮助!

The second BufferedWriter, or rather the second implicit FileWriter, overwrites the file created by the first one. 第二个BufferedWriter或更确切地说第二个隐式FileWriter覆盖第一个创建的文件。

Combine the statements as you suggest, or use append mode (inefficient in this case). 根据您的建议组合语句,或使用追加模式(在这种情况下效率低下)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM