Java – FileWriter is not writing in to a file

filejava

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?

Best Solution

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.