在Java中使用BufferedWriter编写文件

在Java中使用BufferedWriter编写文件,java,eclipse,file-io,filewriter,bufferedwriter,Java,Eclipse,File Io,Filewriter,Bufferedwriter,我正在做一个实验室,我们必须读入一个外部文件,对数据进行一些统计,然后用这些统计数据创建并编写一个新文件。我的程序中除了写文件以外的所有东西都能工作,我不明白为什么我的方法不能工作 BufferedWriter writer; public void writeStats(int word, int numSent, int shortest, int longest, int average) { try { File file = new File("jef

我正在做一个实验室,我们必须读入一个外部文件,对数据进行一些统计,然后用这些统计数据创建并编写一个新文件。我的程序中除了写文件以外的所有东西都能工作,我不明白为什么我的方法不能工作

BufferedWriter writer;

public void writeStats(int word, int numSent, int shortest, int longest, int average)
{
    try
    {
        File file = new File("jefferson_stats.txt");
        file.createNewFile();

        writer = new BufferedWriter(new FileWriter(file));

        writer.write("Number of words: " + word );
        writer.newLine();
        writer.write("Number of sentences: " + numSent );
        writer.newLine();
        writer.write("Shortest sentence: " + shortest + " words");
        writer.newLine();
        writer.write("Longest sentence: " + longest + " words");
        writer.newLine();
        writer.write("Average sentence: " + average + " words");    
    }
    catch(FileNotFoundException e)
    {
        System.out.println("File Not Found");
        System.exit( 1 );
    }
    catch(IOException e)
    {
        System.out.println("something messed up");
        System.exit( 1 );
    }
}

您必须使用以下方法关闭您的BufferedWriter


您必须刷新并关闭写入程序:

writer.flush();
writer.close();

您应该始终使用Java7显式或隐式地关闭opend资源try with resources

    try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
         ...            
    }
此外,还有一个更方便的类来编写文本—java.io.PrintWriter

try (PrintWriter pw = new PrintWriter(file)) {
    pw.println("Number of words: " + word);
    ...
}

close()将隐式调用flush,您不需要从Oracle文档中显式调用flush:
flush:刷新此输出流并强制写出任何缓冲输出字节。刷新的一般约定是,调用它表示,如果先前写入的任何字节已被输出流的实现缓冲,则应立即将这些字节写入其预期目标。
对于缓冲流,建议使用
flush()
,然后使用
close()
在上一个writer.write()之后,您可能需要一个writer.newLine()。
try (PrintWriter pw = new PrintWriter(file)) {
    pw.println("Number of words: " + word);
    ...
}