Android 使用getExternalStoragePublicDirectory时FileNotFoundException
我有从网上下载文件的代码。它适用于有SD卡的手机,但我在没有SD卡的手机上测试了它,发现以下错误:Android 使用getExternalStoragePublicDirectory时FileNotFoundException,android,filenotfoundexception,android-file,android-external-storage,Android,Filenotfoundexception,Android File,Android External Storage,我有从网上下载文件的代码。它适用于有SD卡的手机,但我在没有SD卡的手机上测试了它,发现以下错误: java.io.FileNotFoundException /storage/emulated/0/Movies/65656s5d.mp4 open failed :ENONET (no such file or directory) 这是我在doInBackGround中的代码: 如何解决此问题?您可能需要使用getExternalStorageDirectory。查看文档了解详细信息:环境。
java.io.FileNotFoundException /storage/emulated/0/Movies/65656s5d.mp4 open failed :ENONET (no such file or directory)
这是我在doInBackGround中的代码:
如何解决此问题?您可能需要使用getExternalStorageDirectory。查看文档了解详细信息:环境。getExternalStoragePublicDirectoryEnvironment.DIRECTORY\u电影无效即使设备没有sd卡,它也将始终存在。请检查您的文件,是否存在文件类中的exists方法?设备运行Android 6.0?此代码用于从网络下载文件。无关的您的代码尝试在文件系统上创建文件。
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode() + " "
+ connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
long number = (long) Math.floor(Math.random() * 9000000000L) + 1000000000L;
String destPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)
+ File.separator+number + ".mp4";
output = new FileOutputStream(destPath);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
return "ok";
} catch (Exception e) {
Log.v("this",e.getMessage());
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
Log.v("this",ignored.getMessage());
return ignored.toString();
}
if (connection != null)
connection.disconnect();
}