How do I check if a file exists in Java?

后端 未结 17 2762
盖世英雄少女心
盖世英雄少女心 2020-11-22 00:50

How can I check whether a file exists, before opening it for reading in Java (the equivalent of Perl\'s -e $filename

17条回答
  •  故里飘歌
    2020-11-22 01:14

    File f = new File(filePathString); 
    

    This will not create a physical file. Will just create an object of the class File. To physically create a file you have to explicitly create it:

    f.createNewFile();
    

    So f.exists() can be used to check whether such a file exists or not.

提交回复
热议问题