-4

I want to open a file, write it in a loop (append everything to the previous lines) and then close it. I had already implmented everything in a single method inside the loop and I had a problem similar to this question. So, I'm trying to implement it according to the suggestion that writing and opening must be done in different steps. My code now is like the following:

  PrintWriter out=  createAndOpenFile(fileName);

     for (int i = 0 ; i< test.size(); i++){
             writeToFile(mystring, out);
        }
    out.close();

And the implementation of the above methods are like the following:

  private PrintWriter createAndOpenFile(String fileName) {

        try (FileWriter fw = new FileWriter(fileName);
             BufferedWriter bw = new BufferedWriter(fw);
             PrintWriter out = new PrintWriter(bw)) {
          return out;

        } catch (IOException e) {

            e.printStackTrace();
            return null;
        }

    }

 private void writeToFile(String features, PrintWriter out) {
       out.println(features);
       out.flush();
    }

Can anyone tell me what is wrong with my code?

Update: With "not working" I meant that the file is empty at the end, though created.

Community
  • 1
  • 1
user1419243
  • 1,655
  • 3
  • 19
  • 33

1 Answers1

1

As @khelwood says, out is closed at the return statement. That's expected.

If you do the writeToFile's inside the try, it works (the file will not be empty):

    try (FileWriter fw = new FileWriter("c:/temp/tt.txt");
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter out = new PrintWriter(bw)) {
        writeToFile(mystring, out);
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
Stefan
  • 2,395
  • 4
  • 15
  • 32