尝试将字符串从 Web 写入文件时出现 FileNotFoundException(权限)

FileNotFoundException(permission) when trying to write string from web to file

我正在尝试构建一个在给定 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.call(AsyncTask.java:304)
                                                                                          at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                          at android.os.AsyncTask$SerialExecutor.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;
}
}

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

将此添加到您的 activity

   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);
    }

在您的 activity

中调用此方法
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);
    }
}

希望这对您有所帮助。

Api 6.0 级或以上你需要运行权限