简体   繁体   English

获取目录的文件对象

[英]Getting a file object of a directory

I need a File object pointing to a directory (may not be existing). 我需要一个指向目录的File对象(可能不存在)。 How do I do that? 我怎么做?

Even if I do something like 即使我做类似的事情

File dir = new File("/tmp/something/"); // with trailing slash

dir.isDirectory() is false . dir.isDirectory()false Then I tried dir.mkdir() which returns false, why? 然后我尝试了dir.mkdir() ,它返回false,为什么呢? I dont need the directory to be existing, in fact, I want it to point to a directory that does not exist (I am doing testing). 我不需要该目录存在,实际上,我希望它指向一个不存在的目录(我正在测试)。 How can I achieve this? 我该如何实现?

from javadoc: "true if and only if the file denoted by this abstract pathname exists and is a directory" 来自javadoc:“仅当此抽象路径名表示的文件存在且为目录时,才为true”

If the file does not exists isDirectory() return false. 如果文件不存在,则isDirectory()返回false。 If you are doing testing probably use a stub can be a better option, in unit testing its better try to don't touch external resources like the filesystem. 如果您要进行测试,则使用存根可能是更好的选择,在更好地进行单元测试时,请尽量不要使用文件系统等外部资源。

Use dir.mkdirs() 使用dir.mkdirs()

mkdirs() will create the specified directory path in its entirety where mkdir() will only create the bottom most directory, failing if it can't find the parent directory of the directory it is trying to create. mkdirs()将完整地创建指定的目录路径,其中mkdir()将仅创建最底部的目录,如果找不到要创建的目录的父目录,则失败。

Trailing slash does not matter. 斜杠无关紧要。 File.isDirectory returns false because it returns true if and only if the file denoted by this abstract pathname exists and is a directory File.isDirectory返回false,因为当且仅当此抽象路径名表示的文件存在且为目录时,它才返回true

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

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