2011-04-17 162 views

回答

34

要創建您可以使用下面的代碼目錄:

File dir = new File("path/to/your/directory"); 
try{ 
    if(dir.mkdir()) { 
    System.out.println("Directory created"); 
    } else { 
    System.out.println("Directory is not created"); 
    } 
}catch(Exception e){ 
    e.printStackTrace(); 
} 

要刪除空目錄,你可以使用此代碼:

boolean success = (new File("your/directory/name")).delete(); 
if (!success) { 
    System.out.println("Deletion failed!"); 
} 

要刪除一個非空目錄,你可以使用此代碼:

public static boolean deleteDir(File dir) { 
    if (dir.isDirectory()) { 
     String[] children = dir.list(); 
     for (int i=0; i<children.length; i++) { 
      boolean success = deleteDir(new File(dir, children[i])); 
      if (!success) { 
       return false; 
      } 
     } 
    } 

    return dir.delete(); 
} 

也許您還需要此權限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

這個答案也是一個很好的資源:

How to create directory automatically on SD card

+0

它沒有必要在try catch中包含mkdir()方法,因爲如果f舊的存在,它返回false並沒有拋出異常 – 2015-04-12 12:09:38

19

創建一個目錄,你可以使用

File myDirectory = new File(Environment.getExternalStorageDirectory(), "dirName"); 

if(!myDirectory.exists()) {         
    myDirectory.mkdirs(); 
} 

將其刪除,

myDirectory.delete(); 

不要忘記添加permi裂變:

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" 
+2

不需要檢查目錄是否存在。如果創建目錄,則mkdirs()將返回true,如果目錄已經存在,則返回false。 – 2014-05-21 20:33:51

0

我已創建目錄和子目錄爲我的項目是這樣..

 File root = android.os.Environment.getExternalStorageDirectory(); 

     File dir = new File (root.getAbsolutePath() + "/MP3 Music/"); //it is my root directory 

     File favourite = new File (root.getAbsolutePath() + "/MP3 Music/" + "Favourites"); // it is my sub folder directory .. it can vary.. 

     try 
     { 
      if(dir.exists()==false) 
      { 
        dir.mkdirs(); 
      } 
      /* else 
      { 
       // Toast.makeText(MainActivity.this, "Root Directory is already exists", Toast.LENGTH_LONG).show(); 
      }*/ 

      if(favourite.exists()==false) 
      { 
       favourite.mkdirs(); 
      } 

     } 
     catch(Exception e){ 
      e.printStackTrace(); 

     } 
3
mkdir() for 

File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/abcabcabc"); 
directory.mkdir(); 


mkdirs() for 
File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Mani/abcxyz"); 
    directory.mkdirs(); 
1
new File(Environment.getExternalStorageDirectory(), "DirName").mkdirs(); 
0

,如果你想創建其下

根目錄和子
String root = Environment.getExternalStorageDirectory().toString(); 

File myDir = new File(root + "/rootfoldername"+"/your sub folder name"); 

File dir=new File(root + "/rootfoldername"+"/your sub folder name"); 

myDir.mkdirs(); 

dir.mkdirs(); 
相關問題