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 (java.io.File) 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);
    theDir.mkdir();
  }
}

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.

 

Post new comment

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