简体   繁体   English

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

[英]how to create a folder in android External Storage Directory?

I cannot create a folder in android External Storage Directory.我无法在 android 外部存储目录中创建文件夹。

I have added permissing on manifest,我在清单上添加了许可,

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

Here is my code:这是我的代码:

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

Do it like this :像这样做 :

String folder_main = "NewFolder";

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

If you wanna create another folder into that :如果您想在其中创建另一个文件夹:

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

The difference between mkdir and mkdirs is that mkdir does not create nonexistent parent directory, while mkdirs does, so if Shidhin does not exist, mkdir will fail.之间的区别mkdirmkdirsmkdir不会产生不存在的父目录,而mkdirs呢,所以如果Shidhin不存在mkdir将失败。 Also, mkdir and mkdirs returns true only if the directory was created.此外, mkdirmkdirs仅在创建目录时返回 true。 If the directory already exists they return false如果目录已经存在,则返回 false

The use of Environment.getExternalStorageDirectory() now is deprecated since API level 29, the option is using:从 API 级别 29 起, Environment.getExternalStorageDirectory()的使用现在已被弃用,该选项正在使用:

Context.getExternalFilesDir() . Context.getExternalFilesDir()

Example:例子:

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

I can create a folder in android External Storage Directory.我可以在 android 外部存储目录中创建一个文件夹。

I have added permissing on manifest,我在清单上添加了许可,

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

Here is my code:这是我的代码:

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(); // This will create a Folder // 这将创建一个文件夹

  • inerDire.createNewFile(); // This will create File (For Eg .jpg // 这将创建文件(例如 .jpg
    file)文件)

we can Create Folder or Directory on External storage as :我们可以在外部存储上创建文件夹或目录:

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

and if we want to create Directory or folder on Internal Memory then we will do :如果我们想在内部存储器上创建目录或文件夹,那么我们将这样做:

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

But make Sure you have given Write External Storage Permission.但请确保您已授予写入外部存储权限。 And Remember that if you have no external drive then it choose by default to internal parent directory.请记住,如果您没有外部驱动器,那么它默认选择内部父目录。 I'm Sure it will work .....enjoy code我确定它会工作.....享受代码

getexternalstoragedirectory() is already deprecated. getexternalstoragedirectory()已被弃用。 I got the solution it might be helpful for you.我得到了可能对你有帮助的解决方案。 (it's a June 2021 solution) (这是 2021 年 6 月的解决方案)

Corresponding To incliding Api 30, Android 11 :对应于包括 Api 30、Android 11 :

Now, use this commonDocumentDirPath for saving files.现在,使用这个 commonDocumentDirPath 来保存文件。

Step: 1第1步

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

Step: 2第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 ;

}

Try adding尝试添加

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

and then just save the file as needed to that path, Android OS will create all the directories needed.然后根据需要将文件保存到该路径,Android OS 将创建所有需要的目录。 You don't need to do the exists checks, just set that flag and save.您不需要进行存在检查,只需设置该标志并保存即可。 (Also see : How to create directory automatically on SD card (另请参阅: 如何在 SD 卡上自动创建目录

If you are trying to create a folder inside your app directory in your storage.如果您尝试在存储中的应用程序目录中创建文件夹。

Step 1 : Add Permission第 1 步:添加权限

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

Step 2 : Add the following第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";
}

try {尝试 {

String filename = "SampleFile.txt"; String 文件名 = "SampleFile.txt"; String filepath = "MyFileStorage"; String 文件路径 = "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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM