Search code examples
javabufferedreaderbufferedwriter

Why does this code cause Java to write over the data in a file?


I am not sure as to why the following code causes Java to override the data already in my file every time, when what I want it to do is actually write each new piece of data on a new line. I have included the relevant pieces of code (I understand you might be thinking that there are errors in the variables, but there isn't, the program works fine). Can someone help me understand as to what is causing this, is is the way I am using the file writer?

String DirToWriteFile = System.getProperty("user.dir") + "/VirtualATM.txt"; //Get path to write text file to.

String Details = "Name: " + name + " CardNo: " + CardNo + " Current Balance: " + balance + " overdraft? " + OverDraft + " OverDraftLimit: " + OverDraftLimit + " pin: " + PinToWrite;
    try{
        //Create writer to write to files.
        File file = new File(DirToWriteFile);
        Writer bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));         
        // FileReader reads text files in the default encoding.
        FileReader fileReader = new FileReader("VirtualATM.txt");
        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String CurrentData = "";
        while((bufferedReader.readLine()) != null) {
                line = CurrentData;
                bw.write(CurrentData);
                ((BufferedWriter) bw).newLine();
        }
        bw.write(Details);
        System.out.println("Account created!");

        System.out.println(name + " Your card number is: " + CardNo);
        //  close the reader.
        bufferedReader.close();
        //Close the writer.
        bw.close();

Solution

  • Use the other FileOutputStream constructor, the one that takes a boolean append parameter as the second parameter. Pass in true as this will tell Java to append text to the existing File rather than over-write it.

    i.e., change this:

        File file = new File(DirToWriteFile);
        Writer bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));         
    

    to this:

        File file = new File(DirToWriteFile);
        FileOutputStream fos = new FileOutputStream(file, true); // **note second param?**
        Writer bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF8"));