Reputation: 17
I am using the following code to download a file from a website. But when I go to the sdcard/download folder, the file does not exist.
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);
}
}
});
Please help me how to get the file in the sdcard/download folder.
Thanks In Advance
Upvotes: 1
Views: 2133
Reputation: 3568
Instead of:
new File("sdcard/download/"+targetFileName));
Try:
new File("/sdcard/download", targetFileName));
Notice the leading slash. You wanted an absolute path.
But, this is better because then we don't make assumptions on where the sdcard is mounted.
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(), targetFileName);
Upvotes: 1
Reputation: 2223
I'd advise using the method Environment.getExternalStorageDirectory().toString()
to ensure that you're getting the correct path to your mounted SD.
Your:
FileOutputStream f = new FileOutputStream(new File("sdcard/download/"+targetFileName));
becomes
FileOutputStream f = new FileOutputStream(new File(Environment.getExternalStorageDirectory().toString()+targetFileName));
Upvotes: 0