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?
public static boolean isDirectory(String path) {
return path !=null && new File(path).isDirectory();
}
To answer the question directly.
private static boolean isValidFolderPath(String path) {
File file = new File(path);
if (!file.exists()) {
return file.mkdirs();
}
return true;
}
To check if a string represents a path or a file programatically, you should use API methods such as isFile(), isDirectory().
How does system understand whether there's a file or a folder?
I guess, the file and folder entries are kept in a data structure and it's managed by the file system.
There is no way for the system to tell you if a String
represent a file
or directory
, if it does not exist in the file system. For example:
Path path = Paths.get("/some/path/to/dir");
System.out.println(Files.isDirectory(path)); // return false
System.out.println(Files.isRegularFile(path)); // return false
And for the following example:
Path path = Paths.get("/some/path/to/dir/file.txt");
System.out.println(Files.isDirectory(path)); //return false
System.out.println(Files.isRegularFile(path)); // return false
So we see that in both case system return false. This is true for both java.io.File
and java.nio.file.Path
Please stick to the nio API to perform these checks
import java.nio.file.*;
static Boolean isDir(Path path) {
if (path == null || !Files.exists(path)) return false;
else return Files.isDirectory(path);
}
Clean solution while staying with the nio API:
Files.isDirectory(path)
Files.isRegularFile(path)
String path = "Your_Path";
File f = new File(path);
if (f.isDirectory()){
}else if(f.isFile()){
}
Source: Stackoverflow.com