Search code examples
javabufferedreaderfilewriterbufferedwriter

How can I stop my bufferedWriter from re-writing the text which is already in the file?


I have a BufferedWriter which is being used to write to a file the users details. I have noticed, however, it is not writing to file in the format I want it to, I can't seem to find a method which allows me to write text on a new line without it writing over what is already there or copy out the text already in the file. Is there any way I can edit the following code, to allow it to the above?

    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);
        FileOutputStream fos = new FileOutputStream(file, true);
        Writer bw = new BufferedWriter(new OutputStreamWriter(fos, "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((currentData=bufferedReader.readLine()) != null) {
                line = currentData;
                bw.write(currentData);
                ((BufferedWriter) bw).newLine();
        }
        bw.write(Details);
        System.out.println("Account created!");

There is no problem with the program (all variables work properly and have been declared somewhere) I have only posted a snippet of the code which is relevant to the question. The current output to the file after running it a few times looks like this


Solution

  • I've got it! Change:

        while((currentData=bufferedReader.readLine()) != null) {
                line = currentData;
                bw.write(currentData);
                ((BufferedWriter) bw).newLine();
        }
        bw.write(Details);
    

    to:

    bw.append(Details);
    ((BufferedWriter) bw).newLine();
    

    This ensures that no data will be written twice and it will not copy out any text besides the information gained from the user.