【问题标题】:how to write to a text file without overwriting?如何在不覆盖的情况下写入文本文件?
【发布时间】:2013-05-20 12:29:00
【问题描述】:

关于如何将表单中的属性写入 java 中的文本文件,我陷入了僵局。我知道对此有很多答案,但我找不到任何解决我面临的问题的方法。虽然当我尝试将它们写入文件时表单中有许多属性,但它会被覆盖。 例如:有 3 个属性 当我尝试将它们写入文件时,第三个会覆盖第二个。

这是我到目前为止所做的:

writer = new PrintWriter(new FileWriter("C:/Documents and Settings/Administrator/Desktop/example1.txt"),true);
if(specific attr found)
    writer.println("my data");
writer.flush();
if(another found)
    writer.println("my data");
writer.flush();
if(third attr found)
    writer.println("my data");
writer.flush();
writer.close();

但它不起作用。

【问题讨论】:

  • 尝试摆脱冲洗
  • 您的示例有效且有效。一定有其他内容您没有与我们分享。
  • 您已将 printwriter autoflush 标志设置为 true,您应该删除那些 flush 语句。除此之外,您的 if 语句可能存在问题,找不到第二个属性。

标签: java filewriter printwriter


【解决方案1】:

您可以使用 FileUtils CommonsIO 2.4 API

例子

package com.doc;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class Test {

    public static void main(String[] args) throws IOException {

        File file = new File("test.txt");
        FileUtils.write(file, "\n my data", true);
        FileUtils.write(file, "\n my data", true);
        FileUtils.write(file, "\n my data", true);

    }
}

输出

 my data
 my data
 my data

【讨论】:

  • 谢谢大家...它的工作。在我删除我的冲洗后..@pavel & @farlan 我的 if 语句确实有问题。虽然这是我的一个愚蠢的错误,但无论如何帮助是赞赏:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-27
  • 2016-03-01
  • 2014-04-21
  • 2020-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多