Check if a path represents a file or a folder

Egor picture Egor · Oct 8, 2012 · Viewed 146.4k times · Source

I need a valid method to check if a String represents a path for file or a directory. What are valid directory names in Android? As it comes out, folder names can contain '.' chars, so how does system understand whether there's a file or a folder?

Answer

Baz picture Baz · Oct 8, 2012

Assuming path is your String.

File file = new File(path);

boolean exists =      file.exists();      // Check if the file exists
boolean isDirectory = file.isDirectory(); // Check if it's a directory
boolean isFile =      file.isFile();      // Check if it's a regular file

See File Javadoc


Or you can use the NIO class Files and check things like this:

Path file = new File(path).toPath();

boolean exists =      Files.exists(file);        // Check if the file exists
boolean isDirectory = Files.isDirectory(file);   // Check if it's a directory
boolean isFile =      Files.isRegularFile(file); // Check if it's a regular file