【问题标题】:How to stop overwrite txt file and let it write in new line如何停止覆盖txt文件并让它写入新行
【发布时间】:2019-10-17 12:27:10
【问题描述】:

问题发生在我的 while 代码中,它首先获取用户输入并将其放入文本文件并询问是否要再次回答,但每个用户都这样做并结束循环它只接受最新的用户输入并且只是覆盖用户之前输入的内容。但这不是我想从我的代码中做的。相反,新答案应该在文本文件的新行上。

public static void main(String[] args) throws IOException {
    // TODO code application logic here

    int saldo = 10000;
    String anw = "j";
    int cost;



    try{
    File folder = new File("folderName");
    folder.mkdir();
    File f = new File(folder, "file1.txt"); //file to folder
    f.createNewFile(); //skapar fil
    //Scanner fileIn = new Scanner(f);
    System.out.println("File path" +f.getPath());

   //.----------------------------------
while(anw.equals("j")){

        Scanner in = new Scanner(System.in);
        FileWriter fWriter ;// removed null
        BufferedWriter writr;// removed null

        System.out.println("Ange utgiftspost:"); //post
        String post = in.nextLine();
        System.out.println("Ange kostnad:"); //kost
        cost=in.nextInt();
        in.nextLine();
        saldo = +saldo -cost; 
        System.out.println("saldo:" +saldo);
        System.out.println("Vill du mata in fler uppgifter? (j/n) :");
        anw = in.nextLine();
        String fileContent = "---"+post+"---"+cost+"---"+saldo; 

        fWriter = new FileWriter(f);
        writr = new BufferedWriter(fWriter);
        writr.write(fileContent);
        writr.newLine();                

        if (anw.equals("n")) {
            writr.close();
            //writer.close();
        //System.out.println("---"+post+"---"+cost+"---"+saldo);                

        }
    } //frågan slut
    }//try

    //Scanner fileIn = new Scanner(f);

      catch(Exception e){
  System.err.println(e.getMessage());
} 

    }

【问题讨论】:

    标签: java string filewriter bufferedwriter


    【解决方案1】:

    您正在为每个循环定义新的Scanner*Writer 对象,这会导致内容被覆盖。定义一次并在每次迭代中重用。

    Scanner in = new Scanner(System.in);
    FileWriter fWriter = new FileWriter(f);
    BufferedWriter writr = new BufferedWriter(fWriter);
    
    while (anw.equals("j")) {
        // ...
    }
    

    不要忘记在循环之后关闭资源

    【讨论】:

      【解决方案2】:

      在我之前的question 中,我有@ASKW 的答案可以解决这个问题。 他评论说 BufferedWriter 对于我的特殊情况不起作用。但是单独使用FilterWriterappend 可以解决这个问题。

      【讨论】:

        猜你喜欢
        • 2012-04-19
        • 2017-01-01
        • 2020-06-11
        • 2011-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-11
        相关资源
        最近更新 更多