java.io.FileNotFoundException:/sdcard/testwrite.txt:打开失败:EACCES(权限被拒绝) [英] java.io.FileNotFoundException: /sdcard/testwrite.txt: open failed: EACCES (Permission denied)

查看:131
本文介绍了java.io.FileNotFoundException:/sdcard/testwrite.txt:打开失败:EACCES(权限被拒绝)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助.

我正在开发Android应用程序.

I am developing Android App.

这是问题所在. 我无法在/sdcard写入文件. 怎么了?

Here is the problem. I can't write a file at /sdcard. what is wrong?

开发工具: Android Studio 3.5.2

设备: AVD Pixel 2 API 29

我编码为Permission Request. 我可以使用旧的android设备写入文件. 为什么我不能用此设备写信?

I coded Permission Request. I can write a file with old android device. Why I can't write with this device ?

请帮助.

错误日志

E: Unknown bits set in runtime_flags: 0x8000
E: --> WRITE_EXTERNAL_STORAGE=true
E: --> READ_EXTERNAL_STORAGE=true
E: ====================================================================
E: --> TEST: Writing.. /sdcard/testwrite.txt
E: --> Writing..
E: --> Error..
E: java.io.FileNotFoundException: /sdcard/testwrite.txt: open failed: EACCES (Permission denied)

AndroidManifest.xml

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.myapp.TestWrite">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity.java

MainActivity.java

package com.myapp.TestWrite;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

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

        Log.wtf( "TAG", "--> WRITE_EXTERNAL_STORAGE=" + hasPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE ) );
        Log.wtf( "TAG", "--> READ_EXTERNAL_STORAGE=" + hasPermission( Manifest.permission.READ_EXTERNAL_STORAGE ) );

        if( Build.VERSION.SDK_INT >= 23 )
        if( hasPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE ) )
        if( hasPermission( Manifest.permission.READ_EXTERNAL_STORAGE ) ) {
            writeTest( "/sdcard/testwrite.txt" );
            return;
        }

        Log.wtf( "TAG", "--> Request permission\n" );
        ActivityCompat.requestPermissions(
                this,
                new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                },
                1
        );
    }

    void writeTest( String fn ) {
        Log.wtf( "TAG", "====================================================================" );
        Log.wtf( "TAG", "--> TEST: Writing.. " + fn );
        File file = new File( fn );
        try {
            Log.wtf( "TAG", "--> Writing.." );;
            FileWriter fw = new FileWriter(file, false);
            fw.write( "Test Doc !!!!!" );
            fw.close();
            Log.wtf( "TAG", "--> Success.." );
        } catch( IOException e) {
            e.printStackTrace();
            Log.wtf( "TAG", "--> Error.." );
            Log.wtf( "TAG", e.toString() );
        }
    }

    public boolean hasPermission( String strPerm ) {
        if ( ContextCompat.checkSelfPermission( this, strPerm ) == PackageManager.PERMISSION_GRANTED )
            return true;
        return false;
    }

    @Override
    public void onRequestPermissionsResult( int requestCode, String[] permissions, int[] grantResults ) {
        Log.wtf( "TAG", ":onRequestPermissionsResult\n" );
        switch ( requestCode ) {
            case 1:
            {
                // If request is cancelled, the result arrays are empty.
                if ( grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED ) {
                    Log.wtf( "TAG", "--> Permission granted.\n" );
                    finish();
                    startActivity( getIntent() );
                }
                else {
                    Log.wtf( "TAG", "--> Permission denied. Quitting.\n" );
                    finish();
                }
            }
        }
    }
}

推荐答案

您正在Android 10中运行应用,而清单中未包含旧版支持属性.按照以下建议编辑清单:

You’re running your app in Android 10 without including the legacy support attribute in your manifest. Edit your manifest as per the suggestion below:

<manifest ... >
  <!-- This attribute is "false" by default on apps targeting
       Android 10 or higher. -->
  <application android:requestLegacyExternalStorage="true" ... >
    ...
  </application>
</manifest>

()

请注意,这只是一个临时修复,因为随着下一个android版本的发布,默认情况下它为false.如果文件是应用程序专用的文件,请考虑使用getExternalFilesDir()动态获取路径.在开发人员的网站上阅读更多有关范围存储更改的信息. a>.

Note that is is only a temporary fix, since this is going to default to false with the release of the next android version. If the files are private to your app, consider acquiring the path dynamically using getExternalFilesDir(). read more about the scoped storage changes in the developers' website.

这篇关于java.io.FileNotFoundException:/sdcard/testwrite.txt:打开失败:EACCES(权限被拒绝)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆