When I run the class, it creates an empty 0kb file. Can someone point out where I am going wrong?

I am trying to write something in the filename "aq.txt". 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();
        }
    } 
}

      

+3


source to share


1 answer


You are closing the thread, but not the writer. All data is buffered in the record. 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 entry will close the base one OutputStreamWriter

, which will also close FileOutputStream

.)

Note that I've moved the call flush

to a block try

- you don't want flush

in a block finally

, as if that didn't work (for example due to insufficient disk space), you won't end up closing the stream. I usually do not explicitly close the checkbox, leaving it on close

to do this, but I was warned that there are some situations in which some implementations will silently catch exceptions when flushing :(

+3


source







All Articles