【问题标题】:Write to text file without overwriting previous entry写入文本文件而不覆盖先前的条目
【发布时间】:2016-04-25 16:30:42
【问题描述】:

我正在使用它来写入文本文件。程序打开时工作正常,但是当我关闭并重新打开并再次开始保存时,它会完全覆盖以前的数字。

private void writeNumbers(ArrayList<String> nums)
{
    try 
    {
        PrintStream oFile = new PrintStream("lottoNumbers.txt");
        oFile.print(nums);
        oFile.close();
    }
    catch(IOException ioe)
    {
        System.out.println("I/O Error" + ioe);
    }
}

【问题讨论】:

标签: java file text writing


【解决方案1】:

您是否在启动程序时阅读此文本文件?如果您正在写入的文件已经存在,它总是会覆盖它。如果要将其添加到文件中,则需要在启动程序时将其读入,将该数据保存在某处,然后将旧数据+新数据写入文件。

虽然可能有更简单的方法,但我过去就是这样做的。

【讨论】:

  • 嗯,不,程序启动时我没有阅读它。我只是认为它会继续添加到之前已经添加的数字。估计不是这样的。
  • 不幸的是,事实并非如此。无论如何,都不是您正在使用的代码。尝试做一些研究,可能有比我建议的更简单的方法。
【解决方案2】:

写一个if语句来检查文件是否存在,如果存在你可以使用“file.append”,否则创建一个新的。

public class WriteToFileExample {
    public static void main(String[] args) {
        try {

            String content = "This is the content to write into file";

            File file = new File("/users/mkyong/filename.txt");

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();

            System.out.println("Done");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

【讨论】:

    【解决方案3】:

    你可以试试这个追加模式

    try {
        Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
    }catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    

    FileUtils.writeStringToFile(file, "String to append", true);
    

    【讨论】:

      猜你喜欢
      • 2011-05-08
      • 1970-01-01
      • 2012-04-15
      • 2014-02-05
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2020-03-28
      相关资源
      最近更新 更多