How do I check if a file exists in Java?

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

    Don't. Just catch the FileNotFoundException. The file system has to test whether the file exists anyway. There is no point in doing all that twice, and several reasons not to, such as:

    • double the code
    • the timing window problem whereby the file might exist when you test but not when you open, or vice versa, and
    • the fact that, as the existence of this question shows, you might make the wrong test and get the wrong answer.

    Don't try to second-guess the system. It knows. And don't try to predict the future. In general the best way to test whether any resource is available is just to try to use it.

提交回复
热议问题