在Android Studio中,我收到两个不同的错误,第一个:“找不到项目”,然后:“拒绝访问”。下载后打开文件时会发生这种情况。我有以下权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
正在下载文件,但我无法阅读它们。 以下是我的代码:
//first error by this way
//String PATH = "/data/data/com.myproj.myproj/attafiles/";
//File folder = new File(PATH);
// if (!folder.exists()) {
// folder.mkdirs();
// }
//URL url = new URL(imageURL);
//File file = new File(folder , fileName);
//Second error
URL url = new URL(imageURL);
File file = new File(context.getFilesDir(), fileName);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());fos.close();
Uri path = Uri.fromFile(file);
String fileExtension= MimeTypeMap.getFileExtensionFromUrl(path.toString());
String mimeType= MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, mimeType);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
答案 0 :(得分:0)
首先检查您的清单中是否同时具有以下权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
如果您已经同时使用它们,请在下载后尝试刷新文件路径。 将此方法添加到您的类或Util包中:
public static void updateFile(Context context, String Newpath) {
context.sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
.parse("file://" + Newpath)));
Log.v(TAG, "[updateGallery] Updating gallery");
}
换句话说,尝试使用下一个方法来读取您的文件:
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("fileURL");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
希望它会对你有所帮助。 祝你好运!