繁体   English   中英

写入文本文件而不覆盖先前的条目

[英]Write to text file without overwriting previous entry

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

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);
    }
}

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

尽管可能有一种更简单的方法,但我过去就是这样做的。

编写一个 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();
        }
    }
}

你可以试试这个追加模式

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM