如何在 java 中使用 File.mkdirs() 编写优雅的代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11823748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:30:41  来源:igfitidea点击:

How to write elegant code using File.mkdirs() in java?

javafileiomkdirs

提问by kino lucky

I need a directory to save files but I am not sure whether it exists.
So I need to check if it exists first, and create it if necessary.

我需要一个目录来保存文件,但我不确定它是否存在。
所以我需要先检查它是否存在,并在必要时创建它。

File saveDir = new File("/tmp/appname/savedir/");
if(!saveDir.exists()){
    saveDir.mkdirs(); 
}

As above, there is a question.
Method "saveDir.exists()" returns a boolean value which indicates if the file path exists.

如上,有个问题。
方法“saveDir.exists()”返回一个布尔值,指示文件路径是否存在。

Of course, I could write some redundant and ugly code to work.

当然,我可以编写一些冗余和丑陋的代码来工作。

Is there a way to write some elegant code to achieve this goal?

有没有办法编写一些优雅的代码来实现这个目标?

回答by Adrian Shum

is your question about "redundant" check-directory-exist code, or you need to create a directory and all missing parent directory?

您的问题是关于“冗余”检查目录存在代码的问题,还是您需要创建一个目录和所有缺少的父目录?

I believe both can be easily done by using FileUtils in Apache Commons IO:

我相信这两者都可以通过在 Apache Commons IO 中使用 FileUtils 轻松完成:

FileUtils.forceMkDir(new File("/some/missing/parent/directory/foo"));

回答by Nathaniel

There is always

总有

if(!file.exists() && !file.mkDirs()) { // handle the failed to create situation... }

回答by Stephan

Elegance is more a subjective thing, but if you want to check whether the directories are actually created, check also the return value of File.mkdirs(). If it returns falseit depends on your application on how to handle it (e.g. throw an exception).

优雅更多是一个主观的东西,但如果你想检查目录是否真正创建,还要检查File.mkdirs(). 如果它返回false它取决于您的应用程序如何处理它(例如抛出异常)。

回答by user207421

There is no point in pre-testing. It just introduces a timing window during which the actual status can still change, so you can still be wrong. Just call mkdirs()and test the result it returns. If false, it did nothing; if true, it did something. Whatexactly it did is really of no actual interest.

预先测试没有意义。它只是引入了一个时间窗口,在此期间实际状态仍然可以更改,因此您仍然可能出错。只需调用mkdirs()并测试它返回的结果。如果为假,则什么也不做;如果是真的,它做了一些事情。它究竟做了什么真的没有实际意义。

回答by Alex D

I would create a static method in a utility class which saves a file andautomatically creates all necessary directories at the same time. The code insidethe utility method may be a bit verbose, but this way, you can keep that ugly, verbose code outof your high-level application logic. And in future projects, you can always reuse the utility. After you split this code off into a utility method, it will also be easy to test in isolation.

我将在实用程序类中创建一个静态方法,该方法保存文件并同时自动创建所有必要的目录。代码的实用程序方法可能有点冗长,但这样一来,就可以保持这种丑陋的,冗长的代码你的高层次应用逻辑的。在未来的项目中,您始终可以重复使用该实用程序。将此代码拆分为实用方法后,也可以轻松地进行单独测试。

I recommend you try to think in terms of building utilities and then using the utilities to build the actual application, rather than mixing detailed, low-level code in everywhere. The utilities you write may be useful on later projects, but that's not the primary goal: even if you only use a utility method on one project, and even ifit is only called from oneplace in the higher-level code, it is stillworth it if it helps make the higher-level code clearer. I don't remember which book helped me to get this concept; it may have been The Practice of Programmingby Kernighan and Pike, or The Art of UNIX Programmingby Raymond, or On Lispby Graham -- or probably all three. (Of course, it's also important to know your language's standard library, so you don't start writing utilities which are already written for you.)

我建议您尝试从构建实用程序的角度思考,然后使用这些实用程序来构建实际的应用程序,而不是在任何地方混合详细的低级代码。您编写的实用程序可能对以后的项目有用,但这不是主要目标:即使您只在一个项目中使用一个实用程序方法,即使它只从更高级别代码的一个地方调用,它仍然是如果它有助于使更高级别的代码更清晰,那就值得了。我不记得是哪本书帮助我获得了这个概念;它可能是Kernighan 和 Pike 的The Practice of Programming,或者Raymond 的The Art of UNIX Programming,或者On Lisp格雷厄姆 - 或者可能所有三个。(当然,了解您的语言的标准库也很重要,因此您不必开始编写已经为您编写的实用程序。)

回答by Gautam

As @stephan mentioned in his answer

正如@stephan 在他的回答中提到的

Elegance is more of a subjective thing

优雅更多的是一种主观的东西

But since you asked for it

但既然你要了

import java.io.File;

public class FileBuilder {
    File file;

    public FileBuilder(String path) {
        file = new File(path);
    }

    public FileBuilder createIfDirDoesNotExists() {
        if (!file.exists()) {
            file.mkdirs();
        }
        return this;
    }

    public File getFile() {
        return file;
    }
}

then you can do

那么你可以做

class test {
    public test() {
        File file = new FileBuilder("/tmp/appname/savedir/").createIfDirDoesNotExists().getFile();
    }
}

回答by nitarshs

 File dir = new File(dirPath);
 if(!dir.exists())
     if(!dir.mkdirs()) {//throw or handle exception here.}

You would still need to throw or Handle SecurityException that might be thrown during File.mkdirs()

您仍然需要抛出或处理 File.mkdirs() 期间可能抛出的 SecurityException

回答by RNJ

file.exists() will return whether a directory OR a file exists. You can also use isDirectory() to check if the file path is a directory or not

file.exists() 将返回目录或文件是否存在。您还可以使用 isDirectory() 检查文件路径是否为目录

if (file.isDirectory()){
      //do somethign because this directory already exists
}
else if (file.isFile()){
      //do somethign because this file already exists
}
else {
     boolean created = file.mkdirs();
     if (!created) {
        throw new IOException("Cannot create directory " + file);
     }
}

As to how elegant this is.... I would wrap it in a util method personally to hide some of this extra cruft java makes you write

至于这是多么优雅....我会亲自将它包装在一个 util 方法中,以隐藏一些额外的垃圾 java 让你写