简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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