2

I've been trying to make a simple bank account in Java and want to save the inputted users' name into a .txt doc. Only problem is that the name is replaced on the first line of the text doc each time I run the code.

package bank.account;
import java.util.Scanner;
import java.io.*;

public class ATM 
{
    public static void main(String[] args){


    Scanner sc = new Scanner(System.in);
    BankAccount userAccount = new BankAccount();
    System.out.println("Please enter your name in order to make a new account:");


    String fileName = "name.txt";
    try {
        FileWriter fileWriter =
                new FileWriter(fileName);
        BufferedWriter bufferedWriter = 
                new BufferedWriter(fileWriter);

        String name = sc.nextLine();
        userAccount.setaccName(name);
                bufferedWriter.write(userAccount.getaccName());
                bufferedWriter.close();

    }
    catch(IOException ex) {
            System.out.println(
                "Error writing to file '"
                + fileName + "'");

        }

    System.out.println("Please enter the amount you would like to deposit");
    double money = sc.nextDouble();
    userAccount.deposit(money);
    System.out.println(userAccount.getaccBalance());
    System.out.println(userAccount.getaccName()+ " your balance is " + userAccount.getaccBalance());

    }

}
kr4m
  • 33
  • 1
  • 1
  • 3

2 Answers2

2

You're overwriting the file contents due to the use of new FileWriter(fileName); (read the JavaDoc on that class/constructor). Use new FileWriter(fileName, true); to append to the file instead.

Also note that you'd need to append a newline character ("\n") before the name if the file is not empty otherwise you'll get all the names in one line.

Thomas
  • 87,414
  • 12
  • 119
  • 157
2

This Code will open or create a file and append the new text into a new line.

PrintStream fileStream = new PrintStream(new File("a.txt"));
fileStream.println(userAccount.getaccName());

Also you can create the FileWriter with the param "append = true" and then the outcome will just be appended into a new line.

// FileWriter(File file, boolean append)
FileWriter fileWriter =
                new FileWriter(filePathName, shouldAppend);
LenglBoy
  • 1,451
  • 1
  • 10
  • 24