我使用以下代码从网站下载文件。但是当我转到sdcard / download文件夹时,该文件不存在。
if(et1.equals(example)){
try {
//this is the file you want to download from the remote server
String path ="http://lifecraze.com/sercice_tax_faq.zip";
//this is the name of the local file you will create
String targetFileName = "sercice_tax_faq.zip";
boolean eof = false;
URL u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File("sdcard/download/"+targetFileName));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) > 0 ) {
f.write(buffer,0, len1);
}
f.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent it=new Intent(Example.this,Sucess.class);
startActivity(it);
}
else{
Intent it=new Intent(Example.this,Failed.class);
startActivity(it);
}
}
});
请帮我解决如何在sdcard / download文件夹中获取文件。
提前致谢
答案 0 :(得分:1)
而不是:
new File("sdcard/download/"+targetFileName));
尝试:
new File("/sdcard/download", targetFileName));
注意前导斜杠。你想要一条绝对的道路。
但是,这更好,因为我们不会对SD卡的安装位置做出假设。
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(), targetFileName);
答案 1 :(得分:0)
我建议使用Environment.getExternalStorageDirectory().toString()
方法确保您获得已安装SD的正确路径。
您:
FileOutputStream f = new FileOutputStream(new File("sdcard/download/"+targetFileName));
变为
FileOutputStream f = new FileOutputStream(new File(Environment.getExternalStorageDirectory().toString()+targetFileName));