Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File returns always false for isDirectory and isFile in Java

Tags:

java

file

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());
}
like image 467
newbie Avatar asked Dec 13 '25 01:12

newbie


1 Answers

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).

like image 85
flo Avatar answered Dec 14 '25 15:12

flo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!