简体   繁体   中英

How to create a new folder in android?

I want to create a new folder in external storage. I use this code:

            val folderMain = "name"

        val f = File(getExternalStorageDirectory(), folderMain)
        if (!f.exists()) {
            f.mkdirs()
        }

After executing it works and creates a new folder in internal storage, not in external storage. How can I create a new folder in external storage?

I am 100% sure I have external storage in my device and it has 14 GB space available in it and location is /storage/extSdCard .

I have tested this code on two Samsung phones Android version jellybean and Kitkat but the same result.

You can have the answers to your questions here :

https://developer.android.com/training/data-storage

I also recommend you to check the result of mkdirs() :

if (!f.exists() && !f.mkdirs()) {
    Log.e("mDebug", "Couldn't create " + f.getName());
}

After executing it works and creates a new folder in internal storage, not in external storage.

No, it creates the file in what the Android SDK refers to as external storage .

I am 100% sure I have external storage in my device and it has 14 GB space available in it and location is /storage/extSdCard.

That represents removable storage .

How can I create a new folder in external storage?

Your existing code creates a directory in the root of external storage. You have no ability to write to arbitrary locations on removable storage.

The simplest places to write to on removable storage are in the locations supplied by the getExternalFilesDirs() , getExternalCacheDirs() , and getExternalMediaDirs() methods on a Context . If those return 2+ locations, the second and subsequent ones are on removable storage, and you have full read/write access to them.

try this code:

String fileName = "myfile.zip";
    File ZIP_Directory = new File("/sdcard/MOBstate/");
    ZIP_Directory.mkdirs();        
     File outputFile = new File(PDF_Directory, fileName);
     FileOutputStream fos = new FileOutputStream(outputFile);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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