FileWriter没有将内容写入文件中。

6
我有以下代码。
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();
}

执行后,文件成功创建,但是所创建的文件为空。这个代码有什么问题?

2
写入后尝试刷新。 - Thomas
2
尝试刷新写入器。默认情况下,仅在缓冲区已满或写入器已关闭时才打印结果值。 - Shriram
附注:考虑使用Java SE 7中引入的NIO.2文件API而不是FileWriter。 - Puce
5个回答

21

否则,FileWriter 不会将当前缓冲区刷新,请关闭它。您可以直接调用 flush 方法。

fileWriter.flush()
fileWriter.close()

如果您要关闭文件,就不需要使用flush方法。例如,如果您的程序在一段时间内在文件中输出了一些内容,并且您想在其他地方检查它,则可以使用flush


2
确保在finally子句中调用close()。最好使用try-with-resources。 - Puce
对我来说,问题在于我使用了文件的相对路径名。获取绝对路径后问题得以解决。 - Cole Henrich

4

缺少关闭操作。因此,最后一个缓冲数据没有写入磁盘。

使用try-with-resources也会进行关闭操作,即使出现异常。在关闭之前不需要进行flush操作,因为关闭会将所有缓冲数据刷新到文件中。

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();
}

3

你需要关闭 filewriter,否则当前缓冲区不会刷新,也无法写入文件。

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.

来自Javadoc

关闭流并首先刷新它。一旦流被关闭,进一步的write()或flush()调用将导致抛出IOException。然而,关闭先前已关闭的流没有任何效果。


2

试试这个:

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();
    }
}

1

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();
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接