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

时间:2017-07-12 04:09:44

标签: java android android-permissions filenotfoundexception

我正在尝试构建一个应用程序,在给定网址时从网络下载文件(例如" .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>

以及用于执行下载和写入操作的asynctask实现的代码:

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

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

3 个答案:

答案 0 :(得分: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);
    }

答案 1 :(得分:1)

在您的活动中调用此方法

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

希望这有帮助。

答案 2 :(得分:0)

Api等级6.0或以上,您需要运行时许可