How do I check if a file exists in Java?

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

    Using java.io.File:

    File f = new File(filePathString);
    if(f.exists() && !f.isDirectory()) { 
        // do something
    }
    
    0 讨论(0)
  • 2020-11-22 01:30

    You can use the following: File.exists()

    0 讨论(0)
  • 2020-11-22 01:37
    f.isFile() && f.canRead()
    
    0 讨论(0)
  • 2020-11-22 01:39

    first hit for "java file exists" on google:

    import java.io.*;
    
    public class FileTest {
        public static void main(String args[]) {
            File f = new File(args[0]);
            System.out.println(f + (f.exists()? " is found " : " is missing "));
        }
    }
    
    0 讨论(0)
  • 2020-11-22 01:39

    It's also well worth getting familiar with Commons FileUtils https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html This has additional methods for managing files and often better than JDK.

    0 讨论(0)
提交回复
热议问题