3

我尝试在文件名“aq.txt”中写入一些内容。目录没有问题。

FileOutputStream fos= null;
try{
    String xyz= "You should stop using xyz";
    fos= new FileOutputStream("aq.txt");
    Writer wrt= new BufferedWriter(new OutputStreamWriter(fos));
    wrt.write(xyz);
}    
catch(IOException e){
    System.out.println("Couldn't write to the file: "+e.toString());
}
finally{
    if(fos!=null){
        try{
            fos.flush();
            fos.close();
        }
        catch(Exception e1){
            e1.printStackTrace();
        }
    } 
}
4

1 回答 1

3

您正在关闭,但不是writer。所有数据都缓存在写入器中。改用这个:

Writer writer = null;
try{
    String xyz= "You should stop using xyz";
    writer = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream("aq.txt")));
    writer.write(xyz);
    writer.flush();
}    
catch(IOException e) {
    System.out.println("Couldn't write to the file: " + e.toString());
}
finally{
    if(writer != null){
        try {
            writer.close();
        }
        catch(IOException e1) {
            e1.printStackTrace();
        }
    }
}

(关闭作者将关闭OutputStreamWriter也将关闭的基础FileOutputStream。)

请注意,我已将flush调用移到try块中 - 您不想flushfinally块中,好像失败(例如,您的磁盘空间不足)您最终不会关闭流。无论如何,我通常不会显式刷新,而是让它close这样做,但我已被警告在某些情况下,某些实现会在刷新时静默捕获异常:(

于 2012-03-17T09:01:48.253 回答