How do I check if a file exists in Java?

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

    I know I'm a bit late in this thread. However, here is my answer, valid since Java 7 and up.

    The following snippet

    if(Files.isRegularFile(Paths.get(pathToFile))) {
        // do something
    }
    

    is perfectly satifactory, because method isRegularFile returns false if file does not exist. Therefore, no need to check if Files.exists(...).

    Note that other parameters are options indicating how links should be handled. By default, symbolic links are followed.

    From Java Oracle documentation

提交回复
热议问题