下面的代码包含从服务器下载文件并将其保存在存储器中,当设备具有内部存储器时可以正常工作。
但是,当我尝试与没有内部存储设备,只有外部存储我得到以下例外。
java.io.filenotfoundexception设备上打开失败的eacces(权限被拒绝)
java.io.filenotfoundexception打开失败EACCES(拒绝)
public void downloadFile(String dlUrl, String dlName) {
int count;
HttpURLConnection con = null;
InputStream is = null;
FileOutputStream fos = null;
try {
URL url = new URL(dlUrl);
con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.connect();
is = url.openStream();
String dir = Environment.getExternalStorageDirectory() + Util.DL_DIRECTORY;
File file = new File(dir);
if(!file.exists()){
file.mkdir();
}
Util.LOG_W(TAG, "Downloading: " + dlName + " ...");
fos = new FileOutputStream(file + "/" + dlName);
byte data[] = new byte[1024];
while((count = is.read(data)) != -1){
fos.write(data, 0, count);
}
Util.LOG_D(TAG, dlName + " Download Complete!");
} catch (Exception e) {
Util.LOG_E(TAG, "DOWNLOAD ERROR = " + e.toString());
bServiceDownloading = false;
}
finally{
try {
if(is != null)
is.close();
if(fos != null)
fos.close();
if(con != null)
con.disconnect();
} catch (Exception e) {
Util.LOG_E(TAG, "CLOSE ERROR = " + e.toString());
}
}
}
而且清单文件我有以下几点:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
我已经尝试了很多到目前为止,StackOverflow中的建议似乎没有任何效果。
任何建议可能是什么原因? 顺便说一下Environment.getExternalStorageDirectory()返回/mnt/sdcard/和file.mkdir()返回false。
尝试用'File file = new File(dir +“/”+ dlName);' –
不幸的是结果是一样的。顺便说一句file.mkdir()返回false,多数民众赞成在我认为的问题。 @PankajKumar –
如果您正在仿真器上进行调试,请确保您创建的sd卡支持..或者如果真实设备确保存在sd卡(设备未连接USB) –