首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >BufferedWriter write()不工作

BufferedWriter write()不工作
EN

Stack Overflow用户
提问于 2018-06-02 03:28:47
回答 1查看 58关注 0票数 1

我正在尝试通过以下代码片段写入和写入文件。但是,该文件已创建,但其中并未写入任何内容。我已经测试了lines结构,它是正常的。

代码语言:javascript
复制
try{
    File file = new File("../received/"+nameFiles.get(op-1));
    BufferedWriter bw = new BufferedWriter( new FileWriter( file, true ) );
    for(String index : lines){
        bw.write(index);
        System.out.println(index);
    }
    System.out.println("Arquivo criado");
}catch(IOException ex){
    ex.printStackTrace();
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-02 03:32:30

您的代码中有一些缺陷:

你永远不会刷新BufferedWriter

  • You're永远不会关闭

下面的代码应该可以解决你的问题:

代码语言:javascript
复制
final File file = new File("../received/"+nameFiles.get(op-1));
try(BufferedWriter bw = new BufferedWriter(new FileWriter(file, true) )){
    for(String index : lines){
        bw.write(index);
        System.out.println(index);
    }
    System.out.println("Arquivo criado");
} catch(IOException ex){
    ex.printStackTrace();
}

try with resources在离开try-catch块后调用AutoCloseable#close()方法。无论何时调用close()BufferedWriter还会调用flush(),它最终会写入您的文件。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50649948

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档