如何在Java中创建目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3634853/
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-08-14 02:59:29  来源:igfitidea点击:

How to create a directory in Java?

javadirectory

提问by jimmy

How do I create Directory/folder?

如何创建目录/文件夹?

Once I have tested System.getProperty("user.home");

一旦我测试过 System.getProperty("user.home");

I have to create a directory (directory name "new folder" ) if and only if new folder does not exist.

当且仅当新文件夹不存在时,我必须创建一个目录(目录名称“新文件夹”)。

采纳答案by Jigar Joshi

After ~7 year, I will update it to better approach which is suggested by Bozho.

大约 7 年后,我会将其更新为 Bozho 建议的更好方法。

new File("/path/directory").mkdirs();

Deprecated:

弃用:

File theDir = new File("new folder");

// if the directory does not exist, create it
if (!theDir.exists()) {
    System.out.println("creating directory: " + theDir.getName());
    boolean result = false;

    try{
        theDir.mkdir();
        result = true;
    } 
    catch(SecurityException se){
        //handle it
    }        
    if(result) {    
        System.out.println("DIR created");  
    }
}

回答by Bozho

new File("/path/directory").mkdirs();

Here "directory" is the name of the directory you want to create/exist.

这里的“目录”是您要创建/存在的目录的名称。

回答by Jon Freedman

The following method should do what you want, just make sure you are checking the return value of mkdir()/ mkdirs()

下面的方法应该做你想做的,只要确保你正在检查mkdir()/ mkdirs()的返回值

private void createUserDir(final String dirName) throws IOException {
    final File homeDir = new File(System.getProperty("user.home"));
    final File dir = new File(homeDir, dirName);
    if (!dir.exists() && !dir.mkdirs()) {
        throw new IOException("Unable to create " + dir.getAbsolutePath();
    }
}

回答by ahvargas

You can try FileUtils#forceMkdir

你可以试试FileUtils#forceMkdir

FileUtils.forceMkdir("/path/directory");

This libraryhave a lot of useful functions.

这个有很多有用的功能。

回答by arun

You can also refer makdir() function for creating a new directory in a folder where you want.

您还可以参考makdir()函数在您想要的文件夹中创建一个新目录。

回答by Fathah Rehman P

public class Test1 {
    public static void main(String[] args)
    {
       String path = System.getProperty("user.home");
       File dir=new File(path+"/new folder");
       if(dir.exists()){
           System.out.println("A folder with name 'new folder' is already exist in the path "+path);
       }else{
           dir.mkdir();
       }

    }
}

回答by score

Though this question has been answered. I would like to put something extra, i.e. if there is a file exist with the directory name that you are trying to create than it should prompt an error. For future visitors.

虽然这个问题已经回答了。我想添加一些额外的东西,即如果存在一个与您尝试创建的目录名称相同的文件,那么它应该会提示错误。对于未来的访客。

public static void makeDir()
{
    File directory = new File(" dirname ");
    if (directory.exists() && directory.isFile())
    {
        System.out.println("The dir with name could not be" +
        " created as it is a normal file");
    }
    else
    {
        try
        {
            if (!directory.exists())
            {
                directory.mkdir();
            }
            String username = System.getProperty("user.name");
            String filename = " path/" + username + ".txt"; //extension if you need one

        }
        catch (IOException e)
        {
            System.out.println("prompt for error");
        }
    }
}

回答by Boubakr

This function allows you to create a directory on the user home directory.

此功能允许您在用户主目录上创建目录。

private static void createDirectory(final String directoryName) {
    final File homeDirectory = new File(System.getProperty("user.home"));
    final File newDirectory = new File(homeDirectory, directoryName);
    if(!newDirectory.exists()) {
        boolean result = newDirectory.mkdir();

        if(result) {
            System.out.println("The directory is created !");
        }
    } else {
        System.out.println("The directory already exist");
    }
}

回答by Mouna

  1. Create a single directory.

    new File("C:\Directory1").mkdir();
    
  2. Create a directory named “Directory2 and all its sub-directories “Sub2″ and “Sub-Sub2″ together.

    new File("C:\Directory2\Sub2\Sub-Sub2").mkdirs()
    
  1. 创建单个目录。

    new File("C:\Directory1").mkdir();
    
  2. 创建一个名为“Directory2”的目录及其所有子目录“Sub2”和“Sub-Sub2”。

    new File("C:\Directory2\Sub2\Sub-Sub2").mkdirs()
    

Source: this perfect tutorial, you find also an example of use.

来源:这个完美的教程,您还可以找到一个使用示例。

回答by Matt Bonness

Just wanted to point out to everyone calling File.mkdir()or File.mkdirs()to be careful the Fileobject is a directory and not a file. For example if you call mkdirs()for the path /dir1/dir2/file.txt, it will create a folderwith the name file.txtwhich is probably not what you wanted. If you are creating a new file and also want to automatically create parent folders you can do something like this:

只是想向每个调用的人指出File.mkdir()File.mkdirs()要注意File对象是目录而不是文件。例如,如果您调用mkdirs()path /dir1/dir2/file.txt,它将创建一个名称可能不是您想要的文件夹file.txt。如果您正在创建一个新文件并且还想自动创建父文件夹,您可以执行以下操作:

            File file = new File(filePath);
            if (file.getParentFile() != null) {
                file.getParentFile().mkdirs();
            }