I have below code
try
{
FileWriter fileWriter = new FileWriter(\"C:\\\\temp\\\\test.txt\");
fileWriter.write(\"Hi this is sasi This t
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
before close
is not needed, as a close flushes all buffered data to file.
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();
}
You must close the FileWriter
, otherwise it won't flush the current buffer. You can call the flush
method directly..
fileWriter.flush()
fileWriter.close()
You don't need to use the flush
method if you are closing the file. The flush
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.
Try this:
import java.io.*;
public class Hey
{
public static void main(String ar[])throws IOException
{
File file = new File("c://temp//Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
}
}
You need to close the filewriter
else the current buffer will not flush and will not allow you to write to the file.
fileWriter.flush(); //just makes sure that any buffered data is written to disk
fileWriter.close(); //flushes the data and indicates that there isn't any more data.
From the Javadoc
Close the stream, flushing it first. Once a stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously-closed stream, however, has no effect.
Please try this :
try
{
FileWriter fileWriter = new FileWriter("C:\\temp\\test.txt");
fileWriter.write("Hi this is sasi This test writing");
fileWriter.append("test");
fileWriter.flush(); // empty buffer in the file
fileWriter.close(); // close the file to allow opening by others applications
}
catch(IOException ioException)
{
ioException.printStackTrace();
}