我从网上下载文件的代码。它适用于带有SD卡的手机,但我已经在没有SD卡的手机上进行了测试,我收到了以下错误:
java.io.FileNotFoundException /storage/emulated/0/Movies/65656s5d.mp4 open failed :ENONET (no such file or directory)
这是doInBackGround
中的代码:
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();
}
我该如何解决这个问题?
答案 0 :(得分:0)
您可能想要使用getExternalStorageDirectory
。查看文档以获取详细信息:https://developer.android.com/reference/android/os/Environment.html
答案 1 :(得分:-1)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)
即使设备没有SD卡也无效,它始终存在。请检查您的文件,是否存在(使用File
类中的exists方法)?