空文件构造函数既不是文件也不是目录 [英] Empty File constructor is neither file nor directory
问题描述
以下两种创建文件的方法有什么区别?
What is the difference between the following two methods for creating a file?
new File(System.getProperty("user.dir"));
new File("");
Java将第一个标识为目录,第二个标识为文件和目录!为什么会这样呢?
Java identifies the first one as a directory, and the second one's neither a file nor a directory! Why is that the case?
代码:
public class MainClass {
public static void main(String[] args) throws Exception {
System.out.println("File Created with CurrentDir taken From System Props");
File f1 = new File(System.getProperty("user.dir"));
System.out.println("Absolute Path: " + f1.getAbsolutePath());
System.out.println("isDirectory: " + f1.isDirectory());
System.out.println("isFile: " + f1.isFile());
System.out.println();
System.out.println("File Created with Empty String Path");
File f2 = new File("");
System.out.println("Absolute Path: " + f2.getAbsolutePath());
System.out.println("isdirectory: " + f2.isDirectory());
System.out.println("isFile: " + f2.isFile());
}
}
输出:
File Created with CurrentDir taken From System Props
Absolute Path: D:\Java Workspace\my_Workspace\JavaTest
isDirectory: true
isFile: false
File Created with Empty String Path
Absolute Path: D:\Java Workspace\my_Workspace\JavaTest
isdirectory: false
isFile: false
推荐答案
说明
Explanation
It may seem a little non-intuitive but actually that's just how the class is supposed to work according to its documentation. It's called empty abstract pathname in the documentation:
空的抽象路径名没有前缀和空名称序列.
从您的构造函数File#File(String)
:
通过将给定的路径名字符串转换为抽象路径名来创建新的File实例.如果给定的字符串为空字符串,则结果为空的抽象路径名.
因此File
类实际上将空名称解释为实际名称.当您测试File#isDirectory()
或File#isFile()
时,它会检查是否存在文件或目录,如
So the File
class actually interprets the empty name as actual name. When you test File#isDirectory()
or File#isFile()
it thus checks if there exists a file or directory like
D:\Java Workspace\iTAW_Workspace\JavaTest\<empty>
请注意,我写的<empty>
表示它实际上在这里搜索具有空名的文件.显然,这样的文件不存在,因此结果将始终为false
.再说一次,它不会检查
Note the <empty>
which I wrote to indicate that it actually searches for a file here with the empty name. Obviously such a file can not exist, thus the result will always be false
. So again, it does not check
D:\Java Workspace\iTAW_Workspace\JavaTest\
,而是此目录中的空文件,该文件不存在.
but rather the empty file in this directory, which does not exist.
不幸的是,使用File#toAbsolutePath()
方法时看不到此信息,因为没有表示空名称的.
Unfortunately you don't see this when using the File#toAbsolutePath()
method as there is no representation for an empty name.
请注意,类File
及其相关的所有内容均已已过时.如今,文件IO使用围绕Files
,Paths
和Path
的NIO来完成.该API更加简洁,直观.它也可以在您当前的示例中正常工作:
Note that the class File
and everything related to it is outdated. Nowadays file IO is done using NIO revolving around Files
, Paths
and Path
. This API is much more cleaner and more intuitive. It will also work as intended on your current example:
Files.isDirectory(Paths.get("")); // true
看看文档了解更多信息.
这篇关于空文件构造函数既不是文件也不是目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!