How do I check if a file exists in Java?

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

    By using nio in Java SE 7,

    import java.nio.file.*;
    
    Path path = Paths.get(filePathString);
    
    if (Files.exists(path)) {
      // file exist
    }
    
    if (Files.notExists(path)) {
      // file is not exist
    }
    

    If both exists and notExists return false, the existence of the file cannot be verified. (maybe no access right to this path)

    You can check if path is a directory or regular file.

    if (Files.isDirectory(path)) {
      // path is directory
    }
    
    if (Files.isRegularFile(path)) {
      // path is regular file
    }
    

    Please check this Java SE 7 tutorial.

提交回复
热议问题