How do I check if a file exists in Java?

后端 未结 17 2419
盖世英雄少女心
盖世英雄少女心 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:27

    I would recommend using isFile() instead of exists(). Most of the time you are looking to check if the path points to a file not only that it exists. Remember that exists() will return true if your path points to a directory.

    new File("path/to/file.txt").isFile();
    

    new File("C:/").exists() will return true but will not allow you to open and read from it as a file.

提交回复
热议问题