0

This is the snippet that saves the data entered by the user into the file. This works fine.i.e it creates the file at the wanted location but the problem is that the file created is empty. What is the reason for this ?

JFileChooser save = new JFileChooser();
    int option = save.showSaveDialog( this );
        if( option == JFileChooser.APPROVE_OPTION ) {
            try {
                BufferedWriter writer = new BufferedWriter( new FileWriter( save.getSelectedFile().getPath() + ".txt") );
                String messageToBeSaved = jTextArea2.getText();
                int lengthOfMessage = messageToBeSaved.length();
                writer.write( messageToBeSaved, 0 , lengthOfMessage );
                JOptionPane.showMessageDialog(new JFrame() , "Message saved");
            } catch(Exception exc) {
                System.out.println(exc);
            }

If there is anything wrong with this snippet,please tell where i am going wrong.

Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328

5 Answers5

4

Since it is a buffered writer, you should flush and close it.

Try adding this:

writer.flush();
writer.close();

To be completely correct, you should close your writer in a finally block.

Edit: The flush is not really required since close will flush anyways.

wjans
  • 10,009
  • 5
  • 32
  • 43
  • 3
    You don't need to flush if you are closing, close will flush. – Kaj Jul 20 '11 at 11:36
  • Good point, I guess it's force of habit because of having issues before without flushing. Updated the answer and +1'd yours. – wjans Jul 20 '11 at 12:03
1

You should close the BufferedWriter after you have written data to it. That will flush the buffer, and then close it.

Kaj
  • 10,862
  • 2
  • 33
  • 27
0

You have to close the writer, then the contents of the buffer will be flushed to the disk.

Alexander Pogrebnyak
  • 44,836
  • 10
  • 105
  • 121
0

Probably because you are not flushing the stream.

bluefoot
  • 10,220
  • 11
  • 43
  • 56
0

You should call write.close() when you are done.

PeterMmm
  • 24,152
  • 13
  • 73
  • 111