0
private void AddAccount(String usernamenew, String passwordnew) {
    final String FileName = "F:/TextFiles/loginaccs.txt";
    File file = new File(FileName);
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            bw.write(usernamenew);
            bw.newLine();
            bw.write(passwordnew);
            bw.newLine();
            bw.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
}

In this method, I tried to write two extra lines to a text file, which is a new username and a new password.

After deleting some of the lines, the program deletes everything in the text file and write two lines, which is not what I wanted.

Am I doing something wrong? Thanks in Advance.

1 Answers1

2

After you write to the BufferedWriter, for the file, you then close it, which is fine.

However, you then create another FileOutputStream. In addition, you should not have a reader and writer of the same file at the same time. All you need to do is create the BufferedWriter, write the file and close it.

private void AddAccount(String usernamenew, String passwordnew) {
    final String FileName = "F:/TextFiles/loginaccs.txt";
    File file = new File(FileName);

        try {
           // BufferedReader br = new BufferedReader(new FileReader(file));
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            bw.write(usernamenew);
            bw.newLine();
            bw.write(passwordnew);
            bw.newLine();
            bw.close();

           // FileOutputStream fos = new FileOutputStream(file);      
           // fos.close();

           // br.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
}
Madhawa Priyashantha
  • 9,208
  • 7
  • 28
  • 58
pczeus
  • 7,195
  • 4
  • 34
  • 50
  • But there is another problem: It deletes everything in the file and write two lines. Is there anyway to keep the original text and add the new one? – DeeThreeCay Mar 19 '16 at 12:56
  • Well, that's kind of a different question and has been answered very clearly here (and is very easy to do): http://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java – pczeus Mar 19 '16 at 17:50