'Can we use two buffered writers to write on the same file with java, in the same class?

I have been wondering if I cam use two bufferedWriters to write an external file with java. This is what I did:

But there is only written X in my created file, any ideas ? It seems like the file gets formatted once the second writer starts working.

public void declareVariables() throws IOException {
    try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file))) {

            bufferedWriter.write("Y");
            bufferedWriter.newLine();
                        bufferedWriter.flush();


        } catch (IOException e) {
            e.printStackTrace();
                }
}


public void affectVariables() throws IOException {
    try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file))) {

            bufferedWriter.write("X");
            bufferedWriter.newLine();
            bufferedWriter.flush();



        } catch (IOException e) {
            e.printStackTrace();
        }
}


Solution 1:[1]

to write in a file you have to use FileWriter like this:

public void declareVariables() {
    try {

        FileWriter writer = new FileWriter(new FileWriter("file.txt"), true);
        writer.append("X");
        //try with resources block calls the close method upon exit and which implicitly calls the flush method. 

    } catch (IOException e) {
        e.printStackTrace();
    }
}


public void affectVariables()  {
    try {
            FileWriter writer = new FileWriter(new FileWriter("file.txt"), true);
            writer.append("X");
            //try with resources block calls the close method upon exit and which implicitly calls the flush method. 
        
    } catch (IOException e) {
        e.printStackTrace();
    }
}

You do not need to put close() and flush() because try with resources block calls the close method upon exit and which implicitly calls the flush method. doc: https://docs.oracle.com/javase/7/docs/api/java/io/OutputStreamWriter.html#close()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Louis