How do I check if a file exists in Java?

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

    You can make it this way

    import java.nio.file.Paths;
    
    String file = "myfile.sss";
    if(Paths.get(file).toFile().isFile()){
        //...do somethinh
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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

    0 讨论(0)
  • Simple example with good coding practices and covering all cases :

     private static void fetchIndexSafely(String url) throws FileAlreadyExistsException {
            File f = new File(Constants.RFC_INDEX_LOCAL_NAME);
            if (f.exists()) {
                throw new FileAlreadyExistsException(f.getAbsolutePath());
            } else {
                try {
                    URL u = new URL(url);
                    FileUtils.copyURLToFile(u, f);
                } catch (MalformedURLException ex) {
                    Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    

    Reference and more examples at

    https://zgrepcode.com/examples/java/java/nio/file/filealreadyexistsexception-implementations

    0 讨论(0)
  • 2020-11-22 01:17

    There is specific purpose to design these methods. We can't say use anyone to check file exist or not.

    1. isFile(): Tests whether the file denoted by this abstract pathname is a normal file.
    2. exists(): Tests whether the file or directory denoted by this abstract pathname exists. docs.oracle.com
    0 讨论(0)
  • 2020-11-22 01:18

    Using Java 8:

    if(Files.exists(Paths.get(filePathString))) { 
        // do something
    }
    
    0 讨论(0)
提交回复
热议问题