I have below code
try
{
FileWriter fileWriter = new FileWriter("C:\\temp\\test.txt");
fileWriter.write("Hi this is sasi This test writing");
fileWriter.append("test");
}
catch(IOException ioException)
{
ioException.printStackTrace();
}
after executing it file is created successfully but the created file is empty
so what is wrong with the code?
Try this:
You need to close the
filewriter
else the current buffer will not flush and will not allow you to write to the file.From the Javadoc
Please try this :
Closing was missing. Hence not the last buffered data was not written to disk.
Closing also happens with try-with-resources. Even when an exception would be thrown. Also a
flush
beforeclose
is not needed, as a close flushes all buffered data to file.You must close the
FileWriter
, otherwise it won't flush the current buffer. You can call theflush
method directly..You don't need to use the
flush
method if you are closing the file. Theflush
can be used for example if your program runs for a while and outputs something in a file and you want to check it elsewhere.