FileWriter is not writing in to a file

2020-04-17 04:45发布

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?

标签: java file
5条回答
beautiful°
2楼-- · 2020-04-17 05:01

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();
    }
}
查看更多
Fickle 薄情
3楼-- · 2020-04-17 05:05

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.

查看更多
倾城 Initia
4楼-- · 2020-04-17 05:09

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();
    }
查看更多
狗以群分
5楼-- · 2020-04-17 05:12

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();
}
查看更多
forever°为你锁心
6楼-- · 2020-04-17 05:17

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.

查看更多
登录 后发表回答