1

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

James
  • 338
  • 1
  • 2
  • 16
  • 2
    You want to append new text to the end of the file, rather than replacing the existing contents of the file? – Kenster Sep 30 '14 at 15:59
  • http://stackoverflow.com/questions/9199216/strings-written-to-file-using-bufferedwriter May be helpful – Cory Klein Sep 30 '14 at 16:02

1 Answers1

0

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.

James
  • 338
  • 1
  • 2
  • 16