Reputation: 3
I have made an Android app that downloads a file from a server and saves it to a directory in the internal storage. First the code validates if the link exists and if the link exists, it downloads the file. The file is downloading but when I go Folder and see if file exists, a file exists but that is not the file I had placed on the server. Everything works inside an AsyncTask
Here goes my code:
String fileName = "abc.pdf";
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a typical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/MyApp/");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
Upvotes: 0
Views: 1318
Reputation: 1277
once I am also suffering this problem and at end I making one Generic AsyncTask Class which is just Download file from server and stored in Local folder.In this code Snippet I am always getting mp3 file From server so I am statically set .mp3 format.you can change this code According to your requirement.
@Override
protected File doInBackground(Void... params) {
//File sdCardRoot = Environment.getExternalStorageDirectory()+"/Music";
File file = new File(Environment.getExternalStorageDirectory() + "/" + ConstansClass.FOLDERNAME);
if (!file.exists()) {
file.mkdir();
}
String filename = "YOUR LOCAL STORAGE FILE NAME TITLE";
yourDir = new File(file, filename + ".mp3");
if (yourDir.exists()) {
return yourDir;
}
String url = "YOUR FILE DOWNLOADING URL";
URL u = null;
try {
DebugLog.e("Request Url" + url);
u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(yourDir));
fos.write(buffer);
fos.flush();
fos.close();
DebugLog.d("Download Complete in On Background");
} catch (MalformedURLException e) {
sucess = false;
e.printStackTrace();
} catch (IOException e) {
sucess = false;
e.printStackTrace();
} catch (Exception e) {
sucess = false;
e.printStackTrace();
DebugLog.e("Error ::" + e.getMessage());
}
return yourDir;
}
Parameter
Note
I hope you are Clear with my Idea. Thanks,
Best of Luck
Upvotes: 1