如何用Java建立目錄?

如何建立目錄/文件夾? 函數

一旦我測試了System.getProperty("user.home"); 測試

當且僅當新文件夾不存在時,我才必須建立一個目錄(目錄名稱爲「 new folder」)。 spa


#1樓

您還能夠引用makdir()函數在所需的文件夾中建立新目錄。 code


#2樓

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();
       }

    }
}

#3樓

雖然已經回答了這個問題。 我想添加一些額外的內容,即若是存在一個您要建立的目錄名稱的文件,它將提示錯誤。 對於將來的訪客。 orm

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");
        }
    }
}

#4樓

使用此功能能夠在用戶主目錄上建立目錄。 教程

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");
    }
}

#5樓

  1. 建立一個目錄。 get

    new File("C:\\\\Directory1").mkdir();
  2. 一塊兒建立一個名爲「 Directory2」及其全部子目錄「 Sub2」和「 Sub-Sub2」的目錄。 it

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

資料來源:這個完美的教程 ,您還會發現一個使用示例。 io

相關文章
相關標籤/搜索