0

So I'm using this function to write to text file, but the text file always ends up empty after executing. Can anyone see what the error might be? I've been stuck on this for a while.

public static void writeTextFile(String fileName, String s) {
    FileWriter output = null;
    try {
      output = new FileWriter(fileName);
      BufferedWriter writer = new BufferedWriter(output);
      writer.write(s);
    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      if (output != null) {
        try {
          output.close();
        } catch (IOException e) {
          // Ignore issues during closing
        }
      }
    }

  }
Jordan Gleeson
  • 531
  • 1
  • 4
  • 12
  • 2
    You are not closing bufferwriter!!add this code writer.close() – Naveen May 06 '14 at 07:56
  • I believe you need to use output.flush(); output.close(); methods http://docs.oracle.com/javase/6/docs/api/index.html?java/util/regex/Pattern.html – olyv May 06 '14 at 08:00

4 Answers4

1

After writing your output you should make sure to flush and close the socket, specially because you are using a buffered output.

writer.write(s);
writer.flush();
writer.close();

If you don't do that, the BufferedWriter will wait for additional data, but there does come none and the program execution is stopped suddenly. Using flush here is optional, as when closing it the flush is implicit, but personally I call it everytime I need to be sure that something goes out. Just like when on the toilet ;)

Theolodis
  • 4,977
  • 3
  • 34
  • 53
1

Just change your to include writer.close(); as given below

 try {
      output = new FileWriter(fileName);
      BufferedWriter writer = new BufferedWriter(output);
      writer.write(s);
      writer.close();
    }
//remaining code

The reason your data not saved in the file because , The Data is saved only if you call writer.flush(); And calling the writer.flush() method is enough to just save data. But you need to close the BufferedWriter() like writer.close(); to avoid resource leak. The close() calls flush() method for you before closing the stream.

mahesh
  • 1,311
  • 1
  • 13
  • 26
0

When you use a Buffer to write something, you must close him when you re end

writer.close(); 
Enrique Quero
  • 582
  • 4
  • 12
0

Without closing bufferwriter you cannot see output on text file try to add this code

 writer.close()
Naveen
  • 535
  • 3
  • 14