Java:银行模拟:写入文件,擦除的文本/书写符号

huangapple go评论117阅读模式
英文:

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));

huangapple
  • 本文由 发表于 2020年9月5日 20:41:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63754052.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定