How to append to a file in java using formatter?

别说谁变了你拦得住时间么 提交于 2021-02-04 08:39:04

问题


i have a simple problem. i use this code to add some records in text file using java but every time i run this program, the file is being created again. i wanna to append records without creating file again ?

   Formatter x = null;


    try{

    x = new Formatter("C:\\Users\\Hamada\\Downloads\\products.txt");

    }

    catch(Exception e)

    {

    //System.out.println("NO Database");

    }

    x.format("%d,%s,%s,%s,%d,%d,%d,%d,%d,%d,%d",id, name, type, brand, quantity, day1, month1, year1, day2, month2, year2);

    x.close();

回答1:


You will need to add a FileStream to the Formatter such as the following and write the appendable to the Formatter.

FileWriter f = new FileWriter("C:\\Users\\Hamada\\Downloads\\products.txt", true);
Formatter form = new Formatter(f);

Within the FileWriter pass the "true" parameter to append to the file and not overwrite the current contents.



来源:https://stackoverflow.com/questions/33247705/how-to-append-to-a-file-in-java-using-formatter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!