How to create a directory in the current working directory in Java

What is the simplest way to create a directory called "foo" in the current working directory of my java application (if it doesn't already exist)?

Or, a slightly different angle: Net What is the Java equivalent of createdirectory ("foo")?

Solution

java. The IO package does not have a directory class, but you can use the mkdir() method on the file class:

(new File("Foo")).mkdir()

Note that MKDIR () has two different failure modes:

>"If there is a security manager and its checkwrite() method does not allow the creation of the specified directory", a SecurityException will be thrown. > If the operation fails for other reasons, mkdir() returns false (more specifically, it returns true if and only if the directory has been created.)

No problem with point 1 - if you don't have permission, throw Point 2 is slightly suboptimal for three reasons:

>You need to check the boolean result of this method If the result is ignored, the operation may fail silently. > If you get an error return, you don't know why the operation failed, which makes it difficult to recover or formulate a meaningful error message. > The strict "if only only only" contract wording also means that if the directory already exists, the method returns false

The next warning is that MKDIR () will not create multiple directories at once This is good for a simple example of my directory called "foo"; However, if you want to create a directory named bar in the directory foo (that is, create the directory "foo / bar"), you must remember to use the mkdirs () method

Therefore, to resolve all these warnings, you can use auxiliary methods, as follows:

public static File createDirectory(String directoryPath) throws IOException {
    File dir = new File(directoryPath);
    if (dir.exists()) {
        return dir;
    }
    if (dir.mkdirs()) {
        return dir;
    }
    throw new IOException("Failed to create directory '" + dir.getAbsolutePath() + "' for an unkNown reason.");
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>