I have application for Android, that downloading files from remote server. And my app downloading files much more slowly as ios application the same file at the same Internet connection.
That my code:
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
FileOutputStream output =
context.openFileOutput(new File(context.getFilesDir(), fileName).getName(), Context.MODE_PRIVATE);
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(String.valueOf((int) ((total * 100) / lenghtOfFile)));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
What can help in solving this problem.
Related
i m making an android app to download pdf files from android and then saving them in a folder in internal or external memory.but sometime due to bad internet connection download stops without finshing .like file size is 1.1mb and its only downloaded upto 750kb. now the problem is whether file fully download or not my app showing it as download but in real it is not.so i want to know the exact size of file befor and after download so that i can found whether file is completely download or not.and want to restart the download.
can anybody help me........
my code
String DownloadUrl = "http://www.example.com/books/"+book_name;
String fileName = book_name;
URL url = new URL(DownloadUrl);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
// File SDCardRoot = new File("/storage/emulated/0/documents/docx/stuff/");
File SDCardRoot = new File(Environment.getExternalStorageDirectory()+File.separator+"MybookStore/paper/paperStuff/documents/docx/other/stuff/");
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,fileName);
String file_size = Long.toString(file.length()/1024);
int size_file=Integer.parseInt(file_size);
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 )
{
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
int progress=(int)(downloadedSize*100/totalSize);
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
}
my code
Any reasonable server response header will include a Content-Length key, which will hopefully denote the full length of the resource you’re trying to download.
With that in mind, here's a quick example:
HttpURLConnection connection = null;
InputStream input = null;
OutputStream output = null;
try {
final URL url = new URL(resourceUrl);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
final int length = connection.getContentLength();
int downloaded = 0;
input = url.openStream();
output = new FileOutputStream(targetFile);
final byte[] buffer = new byte[BUFFER_SIZE];
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
downloaded += read;
}
if (downloaded == length) {
// The file was successfully downloaded.
} else {
// The file was not fully downloaded.
}
} catch (IOException e) {
// Handle exception.
} finally {
// Close resources.
}
I am using the following code for downloading file from server:
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(false);
urlConnection.connect();
StorageTools.maintainMemoryEmptyThreshold(25);
if (tempFolderFile.createNewFile()) {
tempFolderFile.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(tempFolderFile);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[8096];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
LOGGER.debug("Progress: downloadedSize: " + downloadedSize + "totalSize: " + totalSize);
}
fileOutput.close();
if (downloadedSize == totalSize) {
LOGGER.info("Downloaded at " + tempFolderFile.getAbsolutePath());
StorageTools.moveFile(tempFolder, targetFolder, fileName);
return true;
}
I trigger the download using a new thread into a tempfolder, move it into required folder upon download completion. How to maintain a cap on the number of active download threads and add remaining downloads to a queue ?
Also, following are my concerns in this regard:
Is there any way in which I can incorporate a threadpool executor for queuing downloads using above function ?
Does the buffersize impact the download speed ?
Please check https://developer.android.com/reference/android/app/DownloadManager.html
buffersize will not impact much. I think it should be in safe limit.
I am trying to create an app that can download music files.
How to download mp3 file in android from a URL and save it in SD card??
I use this code but lenghtOfFile always <=350:
String fileUrl = (String) params[0];
path = (String) params[1];
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
int count;
try {
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
connection .connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = connection .getContentLength();
// downlod the file
input = new BufferedInputStream(url.openStream());
output = new FileOutputStream(path);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
url files :
http://snd1.tebyan.net/1391/12/08_Khaneh_D_117323.mp3
http://snd1.tebyan.net/1393/12/100_Pedar_Va_Madar_D_148797.mp3
and .....
update :
int code= connection.getResponseCode();\\302
String _result= connection.getResponseMessage();\\ found
note :
Files do download in Samsung Galaxy S3, but files do not download in Samsung tablet N8000
You could implement HMTL5 and do it from there, might need some JS...
for 302 response ,you need connection.setInstanceFollowRedirects(true) to follow it. before connection.connect()
I'm having trouble loading PDF files with Japanese characters, since I'm using MuPDF library my implementation is to download the PDF first from the link then open it with MuPDF from the SDcard. Now it cannot be opened since the PDF was not downloaded in the first place.
Here's my code:
try {
URL url = new URL(path[0]);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
// getting file length
int lengthOfFile = urlConnection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(
url.openStream(), 8192);
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(pdfUrl);
pdfFileName = URLUtil.guessFileName(pdfUrl, null, fileExtension);
// Output stream to write file
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().getPath()
+ "/SAMPLE/" + pdfFileName);
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) / lengthOfFile));
// 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());
}
It can download successfully any PDF source links except those with Japanese characters.
My application needs to download some big Files. I use a service for the download an show the progress in a notification. The problem is that during that download time the user can switch from 3g to WIFI. In that case the progress stops but no exception is thrown.
How do I handle this situation properly?
URL url = new URL(myurl);
URLConnection conexion = url.openConnection();
conexion.setReadTimeout(10000);
conexion.setConnectTimeout(10000);
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(targetFilePath);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
updateProgress(downloadNM, downloadNotification, (int)total*100/lenghtOfFile);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
Take a look at the HttpClient-Library. It provides much more options than the URL class, and might help you with your problem.
http://developer.android.com/reference/org/apache/http/client/HttpClient.html