Java File IO - How to test whether a file or directory exists

Java File I/O FAQ: Using Java, how can you test to see if a file or directory exists?

Java test to see if a file or directory exists

Answer: Here's a sample Java method that shows this test. All you have to do is use the exists() method of the File class ( to perform this test.

private void createDirectoryIfNeeded(String directoryName)
  File theDir = new File(directoryName);

  // if the directory does not exist, create it
  if (!theDir.exists())
    System.out.println("creating directory: " + directoryName);

As you can see from the comment, the code checks to see if the directory exists, and if not, it creates it. So, at least in the case of a directory, this method shows not only how to see if a directory exists, but also how to create it if necessary.

Note: While in this example I'm working with a directory, you can use the same test to test whether a file exists or not.


Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.