简体   繁体   中英

Create a file inside a new folder in sdcard

I was trying to create a new file and a new folder inside my sdcard directory, but without any type of progress. I have tried differents code but nobody works. This is my last code that I have tried:

package dev.lordwalrus.alita;

import android.os.Bundle;
import android.os.Environment;

import androidx.appcompat.app.AppCompatActivity;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {
            File newFolder = new File(Environment.getExternalStorageDirectory(), "TestFolder");
            if (!newFolder.exists()) {
                newFolder.mkdir();
            }

            File file = new File(newFolder, "MyTest" + ".txt");
            file.createNewFile();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}

Obviously I have added in my android manifest permission to write and read external storage:

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

I am using android min sdk version 21.

Thank you a lot!

For Android 6.0+ you should ask for permission manually. Please refer to this for more information. Declaring itself doesn't guarantee you can write anything to external storage. Also, starting from Android 10, you should also specify FileProvider. Refer to this

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