【问题标题】:how to create a folder in android External Storage Directory?如何在android外部存储目录中创建一个文件夹?
【发布时间】:2014-09-07 00:09:54
【问题描述】:

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

我在清单上添加了许可,

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

【问题讨论】:

标签: android directory


【解决方案1】:

尝试添加

FPath.mkdirs(); (见http://developer.android.com/reference/java/io/File.html

然后根据需要将文件保存到该路径,Android OS 将创建所有需要的目录。 您不需要进行存在检查,只需设置该标志并保存。 (另见:How to create directory automatically on SD card

【讨论】:

  • 克里斯,我相信是 File.mkdirs(),而不是 FPath?
  • 海报示例中的代码有一个变量调用 FPath ,因此 FPath.mkdirs();
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    这样做:

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

    【讨论】:

    • getExternalStorageDirectory 已弃用,您可以使用替代的 getExternalFilesDir 或其他方法。
    【解决方案4】:

    我们可以在外部存储上创建文件夹或目录:

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

    但请确保您已授予写入外部存储权限。 请记住,如果您没有外部驱动器,那么它默认选择内部父目录。 我确定它会起作用.....享受代码

    【讨论】:

      【解决方案5】:

      试试{

      字符串文件名 = "SampleFile.txt"; 字符串文件路径 = "MyFileStorage";

                      FileInputStream fis = new FileInputStream(myExternalFile);
                      DataInputStream in = new DataInputStream(fis);
                      BufferedReader br =
                              new BufferedReader(new InputStreamReader(in));
                      String strLine;
                      while ((strLine = br.readLine()) != null) {
                          myData = myData + strLine;
                      }
                      in.close();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
                inputText.setText(myData);
                  response.setText("SampleFile.txt data retrieved from External Storage...");
              }
          });
      
          if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
              saveButton.setEnabled(false);
          }
          else {
              myExternalFile = new File(getExternalFilesDir(filepath), filename);
          }
      

      【讨论】:

        【解决方案6】:

        我可以在 android External Storage Directory 中创建一个文件夹。

        我在清单上添加了许可,

        <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
          文件)

        【讨论】:

          【解决方案7】:

          自 API 级别 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();
          }
          

          【讨论】:

            【解决方案8】:

            如果您尝试在存储中的应用目录内创建文件夹。

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

            【讨论】:

              【解决方案9】:

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

              【讨论】:

                【解决方案10】:

                这是原始的,但应该足以让您继续前进 // 在 Data/comexampl 您的应用文件中创建外部文件夹

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

                【讨论】:

                  【解决方案11】:

                  我还发现了另一件事: 我最近遇到了同样的问题,我尝试了 abow 解决方案,但它们没有用...... 我这样做是为了解决我的问题: 我将此权限添加到我的项目清单文件中:

                  &lt;uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/&gt;

                  (加上 READ 和 WRITE 权限)并且我的应用程序运行正常。

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 2020-12-22
                    • 1970-01-01
                    • 1970-01-01
                    • 2020-11-17
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多