我想以编程方式在SD卡内创建一个新目录,我也想删除该目录。我怎么能这样做?
答案 0 :(得分:45)
要创建目录,您可以使用以下代码:
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" />
这个答案也是一个很好的资源:
答案 1 :(得分:23)
要创建目录,可以使用
File myDirectory = new File(Environment.getExternalStorageDirectory(), "dirName");
if(!myDirectory.exists()) {
myDirectory.mkdirs();
}
删除它,
myDirectory.delete();
别忘了添加权限:
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
答案 2 :(得分: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();
答案 3 :(得分:2)
new File(Environment.getExternalStorageDirectory(), "DirName").mkdirs();
答案 4 :(得分: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();
}
答案 5 :(得分: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();