英文:
Java: Bank simulation: Write to file, erased text/writing symbols
问题
如果(choice.equals("ADD")){
System.out.println("当前选择:" + choice);
//写入文件
尝试 {
String filePath = "C:\\Users\\user\\Desktop\\programming\\projects\\java\\RandomStuff\\Bank\\balance.txt";
// System.out.println("您想要添加多少?");
// 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(String.valueOf(balanceToAdd));
out.close();
System.out.println("已添加:" + balanceToAdd);
} //尝试结束
catch(IOException e){
System.out.println("错误(第56行):" + e.getMessage());
}
}
英文:
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());
}
答案1
得分: 1
public FileWriter(String fileName,
boolean append)
我认为你应该使用 append 来编辑你的文件。
BufferedWriter out = new BufferedWriter(new FileWriter(filePath,true));
英文:
public FileWriter(String fileName,
boolean append)
I think you should use append to edit your file.
BufferedWriter out = new BufferedWriter(new FileWriter(filePath,true));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论