2

I am trying to write into a single text file through different classes. I opened the text file from the main class:

public static void main( String[] args ) throws Exception {
    BufferedWriter writer = new BufferedWriter(new FileWriter("src/t1.txt"));
    Parser.getParseTree().print(); // where I called the method
    writer.close();
  }

This is a print() method from another class:

    public static  void print() throws IOException {

            BufferedWriter writer = new BufferedWriter(new FileWriter("src/t1.txt"));
            writer.write("afcad fad fad");
     }

The BufferedWriter writer = new BufferedWriter(new FileWriter("src/t1.txt"));in print() method does not work and nothing prints into the t1.txt file.

0

1 Answer 1

1

Don't have multiple places (methods) that each write to the file on their own.

Simply use one central place that opens the file for writing (probably using try-with-resource) and have any other code call a method at that central place. In other words, all your code should just invoke the same method!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.