[英]FileNotFoundException(permission) when trying to write string from web to file
i am trying to build an application that downloads files (eg ".jpg", ".txt") from the web when given a url. 我正在尝试构建一个在给定URL时从Web下载文件(例如“ .jpg”,“。txt”)的应用程序。 its not really meant to be a real world application, more just an exercise to help me become more comfortable with network and io based code. 它并不是真的要成为现实世界的应用程序,而仅仅是一种练习,可以帮助我更加熟悉基于网络和io的代码。 for now i am just pulling the bytes from the url and then converting them to a string and logging that. 现在,我只是从url中提取字节,然后将它们转换为字符串并将其记录下来。 then from there i want to write this to a file. 然后从那里我想将此写入文件。 the problem i am running into now is that im getting a file not found exception stating that access is denied: 我现在遇到的问题是,即时消息获取文件未找到异常,表明访问被拒绝:
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)
here is my manifest: 这是我的清单:
<?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>
and the code for the asynctask implementation i am using to perform the download and write operation: 以及用于执行下载和写入操作的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;
}
}
i am pretty new to this so i may have made some pretty obvious mistakes. 我对此很陌生,所以我可能犯了一些非常明显的错误。 please help solve this error. 请帮助解决此错误。 thank you. 谢谢。
add this to your 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);
}
call this method in your 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);
}
}
}
and override this method 并重写此方法
@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);
}
}
Hope This helps. 希望这可以帮助。
Api 6.0或更高级别需要运行时权限
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.