【问题标题】:How to add content to files using Java如何使用 Java 向文件添加内容
【发布时间】:2011-09-06 11:58:26
【问题描述】:

我有一个结果被输入到一个文件中。这个结果是在循环中完成的。因此,每次出现新结果时,都必须将其附加到文件中,但它正在被覆盖。我应该使用什么来将我的结果附加到一个文件中?

【问题讨论】:

  • 我可以看看错误信息吗?甚至可能提供一些代码?

标签: java file-io append


【解决方案1】:

试试

BufferedWriter out = null;
try {
    out = new BufferedWriter(new FileWriter("filename", true));
    out.write("aString");
} 
catch (IOException e) {
    // handle exception
}
finally{
    if(out != null){
        try{
            out.close();
        }
        catch(IOException e){
            // handle exception
        }
    }
} 

根据API

构造一个给定的 FileWriter 对象 文件对象。如果第二个参数是 真,那么字节将被写入 文件的结尾而不是 开始。

【讨论】:

    【解决方案2】:

    您应该保持文件打开(有时会更好,但通常不会...)或在append mode 中打开输出流:

    OutputStream os = new FileOutputStream(file, true); 
    

    【讨论】:

      【解决方案3】:

      这里是基本的sn-p

        FileWriter fstream = new FileWriter("out.txt",true);
        BufferedWriter out = new BufferedWriter(fstream);
        out.write("Hello Java 1");
        out.write("Hello Java 2");
      

      另见

      【讨论】:

      • 异常/资源处理留给你
      • @ALL try{ TransformerFactory tFactory = TransformerFactory.newInstance();变压器变压器 = tFactory.newTransformer(); DOMSource 源 = 新 DOMSource(aNode); StreamResult 结果 = new StreamResult(new File("C:/Users/deepu/korkin_lab/sample/testing.xml"));变压器.transform(源,结果); }
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-22
      • 2017-03-09
      • 2014-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      相关资源
      最近更新 更多