简体   繁体   中英

How to stop overwrite txt file and let it write in new line

The problem occurs from my while code, it first takes the user input and put it to the text file and ask if it wants to answer it again but every the user do that and end the loop it just takes the latest user input and just overwrites the previous input user did. But that's not what I want from my code to do. Instead, the new answer should just then be on a new line on the text file.

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

    }

You are defining with each loop new Scanner and *Writer objects which cause the content is overwritten. Define those once and reuse with each iteration.

Scanner in = new Scanner(System.in);
FileWriter fWriter = new FileWriter(f);
BufferedWriter writr = new BufferedWriter(fWriter);

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

Don't forget to close the resources after the loop.

In my previous question , I had @ASKW answer working for this problem. He commented that BufferedWriter for my particular case wouldn't work. But to use FilterWriter alone with append would solve it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM