java check if directory exists

java check if directory exists

To check if a directory exists in Java, you can use the exists method of the File class. This method takes a file or directory path as an argument and returns a boolean value indicating whether the file or directory exists.

Here's an example of how to use the exists method to check if a directory exists:

refe‮:ot r‬lautturi.com
import java.io.File;

public class Main {
  public static void main(String[] args) {
    File dir = new File("/path/to/directory");
    if (dir.exists() && dir.isDirectory()) {
      // directory exists
    } else {
      // directory does not exist
    }
  }
}

In this example, the File object dir represents the directory to be checked. The exists method is used to check if the directory exists, and the isDirectory method is used to verify that the File object represents a directory rather than a file.

You can also use the exists method to check if a file exists, by replacing dir.isDirectory() with dir.isFile() in the if statement.

Note that the exists method only checks for the presence of the file or directory at the specified path, and does not verify that the file or directory is readable or writable. If you need to check for these permissions, you can use the canRead and canWrite methods of the File class.

Created Time:2017-11-03 00:14:48  Author:lautturi