Why file returns false for isFile() method, even when it is file. And when it is directory, it returns false for isDirectory(). Am I doing something wrong? These files/directories I test don't exists, and I need to create these, so that is why I am testing if I should use createFile() or mkdir().
File file = new File("C:/Users/John/Desktop/MyDir/file.txt");
if(!file.exists())
{
System.out.println("Is directory : " + file.isDirectory());
System.out.println("Is file : " + file.isFile());
}
解决方案
In your if you're checking if the file doesn't exist. If it doesn't exist then it's neither a file nor a directory.
Java can't determine if your File object is a file or a directory only with a path string. The String could mean a file or a directory (you can have a folder named "file.txt" or a file with the same name).