Frage

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. 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:

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. 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.

Basically, the newLine() methods are not saving unless I write text directly after them.

Any help is appreciated, as always!

War es hilfreich?

Lösung

The second BufferedWriter, or rather the second implicit FileWriter, overwrites the file created by the first one.

Combine the statements as you suggest, or use append mode (inefficient in this case).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top