简体   繁体   English

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

[英]Write to text file without overwriting previous entry

I'm using this to write to a text file.我正在使用它来写入文本文件。 Works fine while program is open but when I close and reopen and start saving again it completely over writes the previous numbers.程序打开时工作正常,但是当我关闭并重新打开并再次开始保存时,它会完全覆盖以前的数字。

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

Are you reading in this text file upon starting the program?您是否在启动程序时阅读此文本文件? If the file you are writing to already exists, it always will overwrite it.如果您正在写入的文件已经存在,它总是会覆盖它。 If you want it to add to the file, you need to read it in upon starting the program, save that data somewhere, then write the OLD data + the NEW data to the file.如果要将其添加到文件中,则需要在启动程序时将其读入,将该数据保存在某处,然后将旧数据+新数据写入文件。

Although there might be an easier way of doing it, this is how i have done it in the past.尽管可能有一种更简单的方法,但我过去就是这样做的。

write an if statement to check if the file exists, if it exists you can use "file.append" else create a new one.编写一个 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();
        }
    }
}

you can try this append mode你可以试试这个追加模式

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

or或者

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

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

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