check file exists java

前端 未结 3 1920
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条回答
  •  既然无缘
    2020-12-21 08:23

    If you wish to append to the file if it already exists there's no need to check for its existence at all using exists(). You merely need to create a FileWriter with the append flag set to true; e.g.

    PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("foo.txt", true)));
    pw.println("Hello, World");
    pw.close();
    

    This will create the file if it does not exist or else append to the end of it otherwise.

提交回复
热议问题