check file exists java

前端 未结 3 1922
Happy的楠姐
Happy的楠姐 2020-12-21 07:58

I want create text file but if the file already exists it should not create new file but should append the text to the content (at the end) of the existing file. How can I d

3条回答
  •  萌比男神i
    2020-12-21 08:41

    You can use the following code to append to a file which already exists -

    try {
        BufferedWriter out = new BufferedWriter(new FileWriter("filename", true));
        out.write("data");
        out.close();
    } catch (IOException e) { }
    

    If the second argument in FileWriter's constructor is true, then bytes will be written to the end of the file rather than the beginning.

    Quoting Stephen's comment:

    ...passing true as the 2nd argument causes the file to be created if it doesn't exist and to be opened for appending if it does exist.

提交回复
热议问题