如何在Android外部存储目录中创建文件夹?

39

我无法在安卓外部存储目录中创建文件夹。

我在清单文件中添加了权限,

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

这是我的代码:

 String Path = Environment.getExternalStorageDirectory().getPath().toString()+ "/Shidhin/ShidhiImages";
  System.out.println("Path  : " +Path );
  File FPath = new File(Path);
  if (!FPath.exists()) {
        if (!FPath.mkdir()) {
            System.out.println("***Problem creating Image folder " +Path );
        }
  }

试试这个吧:) 希望能对你有所帮助。https://dev59.com/ZnvZa4cB1Zd3GeqP_R4M#41160319 - Agilanbu
11个回答

77

像这样做:

String folder_main = "NewFolder";

File f = new File(Environment.getExternalStorageDirectory(), folder_main);
if (!f.exists()) {
    f.mkdirs();
}

如果您想在其中创建另一个文件夹:

File f1 = new File(Environment.getExternalStorageDirectory() + "/" + folder_main, "product1");
if (!f1.exists()) {
    f1.mkdirs();
}

3
getExternalStorageDirectory已经过时,您可以使用替代方法getExternalFilesDir或其他方法。 - Seyid-Kanan Bagirov
2
@Seyid-KananBagirov请在回答时具体说明。当应用程序被移除或数据被清除时,getExternalFilesDir将被清除。那么,有哪些其他方法呢? - TheRealChx101

13

mkdirmkdirs的区别在于,mkdir不会创建不存在的父目录,而mkdirs会,所以如果Shidhin不存在,mkdir将失败。此外,mkdirmkdirs仅在目录被创建时返回true。如果目录已经存在,则返回false。


10

getexternalstoragedirectory() 已经被弃用。我找到了解决方法,对你可能有帮助。(这是2021年6月的解决方案)

适用于包括Api 30、Android 11的系统:

现在,使用commonDocumentDirPath来保存文件。

步骤1:

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

步骤:2

public  static  File commonDocumentDirPath(String FolderName){
    File dir = null ;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        dir = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+ "/"+FolderName );
    } else {
        dir = new File(Environment.getExternalStorageDirectory() + "/"+FolderName);
    }   
    return  dir ;

}

6

在API Level 29及以上版本中,使用Environment.getExternalStorageDirectory()的方法已经被弃用,可以使用以下选项:

Context.getExternalFilesDir()

示例:

void createExternalStoragePrivateFile() {
    // Create a path where we will place our private file on external
    // storage.
    File file = new File(getExternalFilesDir(null), "DemoFile.jpg");

    try {
        // Very simple code to copy a picture from the application's
        // resource into the external file.  Note that this code does
        // no error checking, and assumes the picture is small (does not
        // try to copy it in chunks).  Note that if external storage is
        // not currently mounted this will silently fail.
        InputStream is = getResources().openRawResource(R.drawable.balloons);
        OutputStream os = new FileOutputStream(file);
        byte[] data = new byte[is.available()];
        is.read(data);
        os.write(data);
        is.close();
        os.close();
    } catch (IOException e) {
        // Unable to create file, likely because external storage is
        // not currently mounted.
        Log.w("ExternalStorage", "Error writing " + file, e);
    }
}

void deleteExternalStoragePrivateFile() {
    // Get path for the file on external storage.  If external
    // storage is not currently mounted this will fail.
    File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
    file.delete();
}

boolean hasExternalStoragePrivateFile() {
    // Get path for the file on external storage.  If external
    // storage is not currently mounted this will fail.
    File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
    return file.exists();
}

4
我可以在安卓外部存储目录中创建一个文件夹。 我已经在清单文件中添加了操作权限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

这是我的代码:

String folder_main = "Images";

File outerFolder = new File(Environment.getExternalStorageDirectory(), folder_main);

File inerDire = new File(outerFolder.getAbsoluteFile(), System.currentTimeMillis() + ".jpg");

if (!outerFolder.exists()) {

    outerFolder.mkdirs();

}
if (!outerFolder.exists()) {

    inerDire.createNewFile();

}
  • outerFolder.mkdirs(); // 这将创建一个文件夹

  • inerDire.createNewFile(); // 这将创建一个文件(例如 .jpg 文件)


1
我们可以在外部存储器上创建文件夹或目录,如下所示:
 String myfolder=Environment.getExternalStorageDirectory()+"/"+fname;
     File f=new File(myfolder);
     if(!f.exists())
     if(!f.mkdir()){
     Toast.makeText(this, myfolder+" can't be created.", Toast.LENGTH_SHORT).show();

    }
    else
     Toast.makeText(this, myfolder+" can be created.", Toast.LENGTH_SHORT).show();
}

如果我们想在内部存储器上创建目录或文件夹,我们可以执行以下操作:

File folder = getFilesDir(); 
File f= new File(folder, "doc_download"); 
f.mkdir();

但请确保您已授予写入外部存储权限。同时请记住,如果您没有外部驱动器,则默认选择内部父目录。我相信它会起作用.....享受编程吧


1
这段原始文本还算足够,可以帮助你开始 // 在 Data/comexampl/your app file 中创建名为 external 的文件夹。请注意保留 HTML 标签。
    File folder = getExternalFilesDir("yourfolder");

        //create folder Internal

   
        File file = new File(Environment.getExternalStorageDirectory().getPath( ) + "/RICKYH");


    if (!file.exists()) {
        file.mkdirs();

        Toast.makeText(MainActivity.this, "Make Dir", Toast.LENGTH_SHORT).show();


    }

1
如果您想在存储中的应用程序目录内创建文件夹。
步骤1:添加权限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

步骤2:添加以下内容。
private String createFolder(Context context, String folderName) {

    //getting app directory
    final File externalFileDir = context.getExternalFilesDir(null);

    //creating new folder instance
    File createdDir = new File(externalFileDir.getAbsoluteFile(),folderName);

    if(!createdDir.exists()){

    //making new directory if it doesn't exist already
        createdDir.mkdir();

    }
    return finalDir.getAbsolutePath() + "/" +  System.currentTimeMillis() + ".txt";
}

0

Chris,我相信应该是使用 File.mkdirs(),而不是 FPath? - William T. Mallard
海报示例中的代码有一个名为 FPath 的变量调用,因此需要执行 FPath.mkdirs()。 - Chris

0
我还发现了另一件事: 最近我也遇到了同样的问题,尝试了上述解决方案,但都没有起作用... 我采取了以下措施来解决我的问题: 我在项目清单文件中添加了此权限:

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

(加上读取和写入权限),我的应用程序正常工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接