Android存储文件到SD卡中


报错:java.io.FileNotFoundException:xxxx: open failed: EACCES (Permission denied)

1. 在AndroidManifest.xml中静态的声明权限

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

无需声明android.permission.READ_EXTERNAL_STORAGE,因为声明写的权限也包括读的权限.

2.Android 6.0后还需要动态的声明权限

package com.selenium.appUpdate;
public class MainActivity extends AppCompatActivity {
    //SD卡下的Download文件夹
    public String FILE_SAVE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/";
    String FILE_NAME = "download.apk";
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //一进入程序就向用户申请权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//android 6.0以上
            //进入程序,申请读写权限
            int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (permission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }
        }
    }
}

在这里插入图片描述

3.注意:File file = new File()并不等于创建了文件

    //SD卡下的Download文件夹
    public String FILE_SAVE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/";
    //文件名
    String FILE_NAME = "download.apk";
    
	//先创建文件夹
	File dir = new File(FILE_SAVE_PATH);
	if(!dir.exists())
	{
	    //mkdirs()与mkdir()的区别在于:mkdirs()会创建一级或者多级目录,mkdir()只会创建一级目录,推荐使用mkdirs()
	    dir.mkdirs();
	}
	//再创建文件
	File file = new File(dir, FILE_NAME);
	if(!file.exists())
	{
	    //这里才等于真正的创建了文件
	    file.createNewFile();
	}

Android 10.0之前的版本有了做好前面3步就行了,但是Android10.0

读写权限授予后报错:Permission denied !

4.android 10.0还需要在AndroidManifest.xml Application中加上android:requestLegacyExternalStorage=“true”

    <application
        android:requestLegacyExternalStorage="true"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_config"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
发布了51 篇原创文章 · 获赞 5 · 访问量 2612

猜你喜欢

转载自blog.csdn.net/qq_45453266/article/details/105129508