3

I try to write something into the filename "aq.txt". There is no problem with the directory.

FileOutputStream fos= null;
try{
    String xyz= "You should stop using xyz";
    fos= new FileOutputStream("aq.txt");
    Writer wrt= new BufferedWriter(new OutputStreamWriter(fos));
    wrt.write(xyz);
}    
catch(IOException e){
    System.out.println("Couldn't write to the file: "+e.toString());
}
finally{
    if(fos!=null){
        try{
            fos.flush();
            fos.close();
        }
        catch(Exception e1){
            e1.printStackTrace();
        }
    } 
}
slhck
  • 36,575
  • 28
  • 148
  • 201
Deepak behera
  • 651
  • 1
  • 5
  • 8
  • In future, please use spaces rather than tabs when posting on SO, so that your code will be formatted correctly. – Jon Skeet Mar 17 '12 at 09:05

1 Answers1

3

You're closing the stream, but not the writer. All the data is buffered in the writer. Use this instead:

Writer writer = null;
try{
    String xyz= "You should stop using xyz";
    writer = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream("aq.txt")));
    writer.write(xyz);
    writer.flush();
}    
catch(IOException e) {
    System.out.println("Couldn't write to the file: " + e.toString());
}
finally{
    if(writer != null){
        try {
            writer.close();
        }
        catch(IOException e1) {
            e1.printStackTrace();
        }
    }
}

(Closing the writer will close the underlying OutputStreamWriter which will close the FileOutputStream too.)

Note that I've moved the flush call into the try block - you don't want to flush in the finally block, as if that fails (e.g. you're out of disk space) you won't end up closing the stream. I normally don't explicitly flush anyway, leaving it to close to do that, but I have been warned that there are some situations in which some implementations will silently catch exceptions while flushing :(

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194