The file always returns false for isDirectory and isFile in Java

Why does the file return false for the isFile() method, even if it is a file. And when it is a directory, it returns false for isDirectory() . Am I doing something wrong? These files / directories that I am testing do not exist and I need to create them, so I am testing whether to 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()); } 
+2
java file
source share
5 answers

In your if you check if the file exists. If it does not exist, then this is neither a file nor a directory.

Java cannot determine if your File object is a file or directory with just a path string. A string can mean a file or directory (you can have a folder named "file.txt" or a file with the same name).

+10
source share

What you do says if it does not exist. If it does not exist, it is neither a file nor a directory. Your logic should be wrong as you should use:

 if(file.exists()){ 
+2
source share

You are using isDirectory() and isFile() in a file object that does not exist. Both of these methods return false if the specified file does not already exist, according to the documentation.

+2
source share

Your program only outputs if if(!file.exists()) , which means that if the file does not exist, it will tell you if file.isFile() . That is, since the file does not exist, your program outputs only False.

0
source share

How can it be a file or directory until it exists? On Linux and Windows (although Explorer itself does not allow inclusion . ), file.txt is a valid name for the file and directory, so Java cannot know how you (or your user) are intended to use it.

0
source share

All Articles