0

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);
    }
}
dbc
  • 104,963
  • 20
  • 228
  • 340
CSharpDude
  • 15
  • 4
  • 4
    Possible duplicate of [File Write - PrintStream append](http://stackoverflow.com/questions/8043356/file-write-printstream-append) – Calvin P. Jan 20 '16 at 01:03

3 Answers3

0

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.

Tim E
  • 1
  • 3
  • Hmm no, I'm not reading it when the program starts.. I just thought that it would keep adding to the previous numbers already added. Guess that wasn't the case. – CSharpDude Jan 20 '16 at 01:15
  • Ya unfortunately thats not the case. Not with the code you're using anyway. Try doing some research, there is probobly a simpler way then what i suggested. – Tim E Jan 20 '16 at 01:24
0

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();
        }
    }
}
Arsaceus
  • 293
  • 2
  • 19
0

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);
Jemo Mgebrishvili
  • 5,187
  • 7
  • 38
  • 63