【问题标题】:FileNotFoundException(permission) when trying to write string from web to file尝试将字符串从 Web 写入文件时出现 FileNotFoundException(权限)
【发布时间】:2017-07-12 04:09:44
【问题描述】:

我正在尝试构建一个应用程序,当给定一个 url 时,它可以从 web 下载文件(例如“.jpg”、“.txt”)。它并不是真的要成为一个真实世界的应用程序,而只是一个练习,以帮助我更加熟悉基于网络和 io 的代码。现在我只是从 url 中提取字节,然后将它们转换为字符串并记录下来。然后从那里我想把它写到一个文件中。我现在遇到的问题是我得到一个文件未找到异常,说明访问被拒绝:

07-11 21:03:14.458 19072-20051/com.example.zacharymcdaniel.webdownloader E/AsyncDownload: network errorjava.io.FileNotFoundException: /sdcard/-1157023572 (Permission denied)
                                                                                      java.io.FileNotFoundException: /sdcard/-1157023572 (Permission denied)
                                                                                          at java.io.FileOutputStream.open(Native Method)
                                                                                          at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
                                                                                          at java.io.FileOutputStream.<init>(FileOutputStream.java:169)
                                                                                          at com.example.zacharymcdaniel.webdownloader.AsyncDownload.doInBackground(AsyncDownload.java:60)
                                                                                          at com.example.zacharymcdaniel.webdownloader.AsyncDownload.doInBackground(AsyncDownload.java:23)
                                                                                          at android.os.AsyncTask$2.call(AsyncTask.java:304)
                                                                                          at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                          at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
                                                                                          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                                          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                                          at java.lang.Thread.run(Thread.java:761)

这是我的清单:

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_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">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

以及我用来执行下载和写入操作的异步任务实现代码:

public class AsyncDownload extends AsyncTask<Void, Void, Void>{
private static final String TAG = "AsyncDownload";
private static final String STORAGE_LOCATION = "/sdcard/"; //android directory picker is needed

private URL url;
private ArrayList<Byte> bytes = new ArrayList<>();

public AsyncDownload(URL url){
    this.url = url;
}

@Override
protected Void doInBackground(Void... params){

    try{
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        int c;
        while ((c = in.read()) != -1){
            buffer.write(c);
        }

        Log.i(TAG, buffer.toString());

        Random rand = new Random(4L);
        String temp = String.valueOf(rand.nextInt());

        String finalLocation = STORAGE_LOCATION + temp;

        File file = new File(finalLocation);
        file.getParentFile().mkdirs();
        file.setWritable(true);
        file.setReadable(true);

        FileOutputStream fOut = new FileOutputStream(file);
        fOut.write(buffer.toByteArray());
        fOut.flush();
        fOut.close();
        FileInputStream fIn = new FileInputStream(finalLocation);

        String reRead = new String();
        int a;
        while ((a = fIn.read()) != -1){
            reRead += a;
        }

        Log.i(TAG, reRead);

        //this section is for automatic file naming
        /*Random rand = new Random(5L);
        String fileNumber = String.valueOf(rand.nextInt());
        StringBuilder sb = new StringBuilder();
        sb.append(fileNumber).append("download"); //definitely needs work

        Log.i(TAG, sb.toString());*/

        //FileOutputStream fOut = new FileOutputStream()

    }catch (IOException ioe){
        Log.e(TAG, "network error" + ioe.toString(), ioe);
    }


    return null;
}
}

我对此很陌生,所以我可能犯了一些非常明显的错误。请帮助解决此错误。谢谢。

【问题讨论】:

  • 您在哪个 api 级别上运行?从 6.0 或更高版本开始,如果您写入外部存储,则必须询问用户运行时以获得许可。如果您写入应用特定的存储空间,则不需要它。
  • 如果你是在安卓6以上的设备上测试,你需要请求读写权限
  • 你确定路径正确吗?

标签: java android android-permissions filenotfoundexception


【解决方案1】:

将此添加到您的活动中

   if (ContextCompat.checkSelfPermission(context,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(InterviewListActivity.this,
                new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_EXT_STORAGE);
    }

【讨论】:

  • 这只是必要的一半。
【解决方案2】:

在您的活动中调用此方法

protected void checkPermissions() {
            final int writeExternalPermissionCheck = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);



    if (writeExternalPermissionCheck != PackageManager.PERMISSION_GRANTED {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    Constant.REQUEST_CODE_ASK_PERMISSIONS);
        }
    } 
}

并覆盖此方法

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case Constant.REQUEST_CODE_ASK_PERMISSIONS:
            if (grantResults!=null) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    //Call ur save method here or change the variable value true
                } else {
                   Logger.toast(this, "Please enable write permission from Apps); 

                }
            }
            break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

希望这会有所帮助。

【讨论】:

    【解决方案3】:

    Api level 6.0 或以上需要运行时权限

    【讨论】:

      猜你喜欢
      • 2016-05-19
      • 2021-11-25
      • 1970-01-01
      • 2015-03-06
      • 1970-01-01
      • 1970-01-01
      • 2017-03-27
      • 2011-12-23
      • 1970-01-01
      相关资源
      最近更新 更多