As a way to learn java, I attempted to write something simulating a bank(adding or removing numbers). I succeeded in creating a file(if one does not exist already), and then read from it, but when I attempt to write to it, it fails. I started with FileWriter, where it just erased the text in the document(balance.txt). I then tried BufferedWriter, and it wrote to the document, but it was just symbols instead of actual text/numbers. I’m aware that I’m a newbie when it comes to coding, but is there a solution to this? Thank you.
if (choice.equals("ADD")){ System.out.println("Currently selected: " + choice); //write to file try { String filePath = "C:\Users\user\Desktop\programming\projects\java\RandomStuff\Bank\balance.txt"; // System.out.println("How much would you like to add?"); // Scanner inputAdd = new Scanner(System.in); // String balanceToAdd = inputAdd.nextLine(); // writeToFile.write(balanceToAdd); int balanceToAdd = 1; BufferedWriter out = new BufferedWriter(new FileWriter(filePath)); out.write(balanceToAdd); out.close(); System.out.println("Added: " + balanceToAdd); } //try end catch(IOException e){ System.out.println("Error(line56): " + e.getMessage()); }
Advertisement
Answer
public FileWriter(String fileName, boolean append)
I think you should use append to edit your file.
BufferedWriter out = new BufferedWriter(new FileWriter(filePath,true));