简体   繁体   English

对于isDirectory,文件返回false,而Java中的isFile

[英]File returns always false for isDirectory and isFile in Java

Why file returns false for isFile() method, even when it is file. 为什么文件对于isFile()方法返回false,即使它是文件。 And when it is directory, it returns false for isDirectory() . 当它是目录时,它为isDirectory()返回false。 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() . 我测试的这些文件/目录不存在,我需要创建这些,所以这就是我测试是否应该使用createFile()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你正在检查文件是否不存在。 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. Java无法确定您的File对象是文件还是仅包含路径字符串的目录。 The String could mean a file or a directory (you can have a folder named "file.txt" or a file with the same name). String可以表示文件或目录(您可以拥有名为“file.txt”的文件夹或具有相同名称的文件)。

What you are doing is saying if it doesn't exist. 你正在做的是说它是否不存在。 If it doesn't exist it is neither a file or directory. 如果它不存在,则它既不是文件也不是目录。 Your logic must be wrong as you should use: 您的逻辑肯定是错误的,因为您应该使用:

if(file.exists()){

You're using isDirectory() and isFile() on a file object that doesn't exist. 您在不存在的文件对象上使用isDirectory()isFile() Both of these methods return false if the specified file does not exist yet, as per the documentation. 如果指定的文件尚不存在,则根据文档,这两个方法都返回false

Your program only prints out if if(!file.exists()) , which means that if the file doesn't exist, it will then tell you if file.isFile() . 你的程序只打印if if(!file.exists()) ,这意味着如果文件存在,它会告诉你file.isFile() That is, because the file doesn't exist then your program only prints out False. 也就是说,因为该文件不存在,那么您的程序只打印出False。

How can it be a file or a directory until it exists? 它是如何存在的文件或目录? In Linux and Windows (though Explorer itself doesn't allow you to include a . ), file.txt is a valid name for both a file and a directory, so Java couldn't possibly know how you (or your user) intended to use it. 在Linux和Windows中(虽然Explorer本身不允许你包含. ), file.txt是文件和目录的有效名称,因此Java无法知道你(或你的用户)的意图用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM