I want to download a video file (extension 3gp) from a certain http address. My application starts downloading, but it stops after downloading 9216 bytes. The file length is 1734741. I tried to increase the heap (because I got some warning about increasing the heap size) by including the following line in the Manifest file:
android:largeHeap="true"
It does not help. Here is the fragment of the java code that deals with downloading:
protected String doInBackground(String... sUrl) {
byte[] data = new byte[8];
double total = 0;
int count = 0;
FileOutputStream fos = null;
BufferedOutputStream output = null;
try {
Log.v("Here","the address is " + sUrl[0]);
URL url= new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
Log.v("File ", "length = " + connection.getContentLength());
// this will be useful so that you can show a typical 0-100% progress bar
double fileLength = (Math.log10((double)connection.getContentLength()));
Log.v("DoInBackground","file length = " + fileLength);
if (fileLength <= 0)
fileLength = (long)(Math.log10(1734741.0));
Log.v("DoInBackground","again file length = " + fileLength);
// download the file
BufferedInputStream input = new BufferedInputStream(connection.getInputStream());
Log.v("Input ","is " + input);
Log.v("Output ","is " + Environment.getExternalStorageDirectory().getPath());
File f = new File(Environment.getExternalStorageDirectory().getPath() + "/twokids.3gp");
f.setWritable(true,true);
try {
fos = new FileOutputStream(f);
} catch (FileNotFoundException fnfe) {
fnfe.getStackTrace();
} catch (SecurityException se) {
se.getStackTrace();
}
output = new BufferedOutputStream(fos); /////????????
int i = (int)(Math.pow(10,(Math.log10(total) + 2 - fileLength)));
while ((count = input.read(data)) != -1) {
Log.v("Count","= " + count);
total += count;
Log.v("Total " + total,"Count " + count);
// publishing the progress....
if ((int)(total * 100 / fileLength) == 0)
i = i + 1;
Log.v("Progress","Increment" + i);
/////////////task.publishProgress(i);
prgs.setProgress(i);
SystemClock.sleep(1000);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (IOException ioe) {
ioe.getStackTrace();
}
catch (Exception e) {
e.getStackTrace();
}
return null;
}
The application uses a Progress Bar to show the progress of the download. Because the file length is quite big (1734741 bytes), I did logarithmic calculations. Also, I have several Log.v messages to see what's going on, I hope this does not hamper understanding of the code.
Anyway, my question refers only to the incomplete downloading of the 3gp file.
What can I do to download the video file? Any idea? Thanks in advance for the help.
Related
I have a strange issue in downloading files in my android application all the files without space can be downloaded but when I have a space in my filename the file will not be downloaded for example:
Will not be download but this link:
http:..../DIV/Bon de Commande.pdf
will be downloaded:
http:..../DIV/POLITIQUE_QUALITE_V6.doc
This how I download file:
protected String downloadfile(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
SharedPreferences myPreference= PreferenceManager.getDefaultSharedPreferences(getContext());
String path=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Document" ;
String Fichename=sUrl[0].replace(myPreference.getString("lientelecharge", ""), "");
String filePath=path+"/"+Fichename;
File file = new File(filePath);
if(file.exists()) {
}else{
// download the file
input = connection.getInputStream();
File folder = new File(path);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
output = new FileOutputStream(path+"/"+Fichename);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (fileLength > 0) // only if total length is known
output.write(data, 0, count);
}
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
Any help would be appreciated
Petrus is right - you have to urlencode string like:
String addressToGo = URLEncoder.encode("www.123.com/55 U.doc", "utf-8");
More ways to encode the string can be found at (my favourite one is without extra libraries): URL encoding in Android
Android- Saving File (Input & Output Stream) throws Exception (open failed: EINVAL (Invalid argument)) in Pre-lollipop devices
I am downloading a file from URL (www.xyz.in/file/9) and saving in SD CARD.
Folder created code:
try {
//String folder_name = "NewFolder";
File f = new File(Environment.getExternalStorageDirectory(), "Venky");
if (!f.exists()) {
f.mkdirs();
}
} catch (Exception e) {
Log.v("MTV", " createFileDirectory exception" + e);
}
Below I posted a (Download and Saving file) code,
In android lollipop, It works fine to download and saved the file in SD Card.
it doesn't works on Pre-lolipop devices. It throws Exception.
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conection.getContentLength();
String depo = conection.getHeaderField("Content-Disposition");
String depoSplit[] = depo.split("filename=");
filename = depoSplit[1].replace("filename=", "").replace("\"", "").trim();
filename=filename.trim();
String Filetype = conection.getContentType();
Log.v("fileName", " " + filename + " FileLength " + lenghtOfFile + " Filetype " + Filetype);
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().toString() + "/Venky/" + filename);
Log.v("", "" + Environment.getExternalStorageDirectory().toString() + "/" + R.string.app_name + "/" + filename);
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();
DownloadSucess = true;
} catch (Exception e) {
DownloadSucess = false;
Log.e("Error: ","Download Exception "+ e);
}
return null;
}
Logcat (Exception):
>E/Error:: Download Exception java.io.FileNotFoundException: /storage/sdcard0/Venky/FileName : smile-please.png: open failed: EINVAL (Invalid argument)
Note: In manifest, Both WRITE_EXTERNAL_STORAGE & READ_EXTERNAL_STORAGE permissions are used.
The value of your variable filename is FileName : smile-please.png and not -what you think- smile-please.png.
Just log the contents of filename before use.
I guess you should first try to create that directory, the file and then check whether them exists or not.
String path = Environment.getExternalStorageDirectory().toString() + "/Venky/";
File dir = new File(path);
boolean created = dir.mkdir();
if (created) {
File fp = new File(path + filename);}
I want to download all mp3 files from server one by one and save into sd card folder. I have no any errors or exception but mp3 does not downloaded and does not show in SD card. Can someone help how to solve this issue.Here is my code.
if (imageName.endsWith(mp3_Pattern))
{
str_DownLoadUrl = namespace + "/DownloadFile/FileName/" + imageName;
Log.e("######### ", "str_DownLoadUrl = " + str_DownLoadUrl);
download_Mp3File(str_DownLoadUrl);
strDownLoadStatus = "1";
dbhelper.update_DownLoadStatus(imageName, strDownLoadStatus);
}
void download_Mp3File(final String fileUrl) {
new AsyncTask<String, Integer, String>()
{
#Override
protected String doInBackground(String... arg0)
{
int count;
File file = new File(newFolder, System.currentTimeMillis() + imageName);
try
{
URL url = new URL(fileUrl);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(file);
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();
} catch (Exception e) {
}
return null;
}
}.execute();
}
place a breakpoint in inputstream object to see is there any stream. then debug output stream to see the results.
Gives an Error Error : close failed: EIO (I/O error) when i delete file which is currently writing mode.
Actually i am downloading file using AsyncTask and i can cancel this download in between.
For stop this download i am deleting that file and checking continuously in while loop of writing data that file is exists or not, if file not found then i am breaking that loop and returning to onPostExecute but its throwing an error.
So how can i remove that error and use output.flush() and output.close() properly?
MyCode is:
#Override
protected String doInBackground(Void... params) {
int count;
try {
URL url = new URL(taskHolder.fileUrl);
URLConnection connection = url.openConnection();
connection.connect();
InputStream input = new BufferedInputStream(url.openStream());
outputDir = PROCESSING_PATH + taskHolder.fileName;
OutputStream output = new FileOutputStream(outputDir);
byte data[] = new byte[1024*4];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
/**
* When user cancelling downloads,
* file will be deleted from that
* folder so here have to check
* file is exists or not.
*/
if(!(new File(outputDir).exists())) {
returnValue = "cancelled";
break;
}
}
returnValue = "1";
output.flush();
returnValue = "2";
output.close();
returnValue = "3";
input.close();
returnValue = "4";
} catch (Exception e) {
Log.e(TAG, "Error : "+e.getLocalizedMessage() + " : " + returnValue);
returnValue = null;
}
return returnValue;
}
In my android app I must download some video from url. For this I use this function :
private void saveVideoToSDcard(String video) throws IOException {
URL url = new URL(video);
long startTime = System.currentTimeMillis();
String name = video.substring(video.lastIndexOf("/") + 1);
System.out.println("image download beginning: " + name);
// Open a connection to that URL
ucon = url.openConnection();
// this timeout affects how long it takes for the app to realize there's
// a connection problem
ucon.setReadTimeout(TIMEOUT_CONNECTION);
ucon.setConnectTimeout(TIMEOUT_SOCKET);
// Define InputStreams to read from the URLConnection.
// uses 3KB download buffer
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
FileOutputStream outStream = new FileOutputStream(
Environment.getExternalStorageDirectory() + "/Downloads/"
+ name);
byte[] buff = new byte[5 * 1024];
// Read bytes (and store them) until there is nothing more to read(-1)
int len;
while ((len = inStream.read(buff)) != -1) {
outStream.write(buff, 0, len);
}
// clean up
outStream.flush();
outStream.close();
inStream.close();
System.out.println("download completed in "
+ ((System.currentTimeMillis() - startTime) / 1000) + " sec");
}
and I call this function on onCreate() method :
for (int j = 0; j < jArray.length(); j++) {
if (target[j].endsWith(".mp4")) {
System.out.println("video de downloadat");
String name = target[j]
.substring(target[j].lastIndexOf("/") + 1);
try {
saveVideoToSDcard(target[j]);
target[j] = Environment.getExternalStorageDirectory()
+ "/Downloads/" + name;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
where target[] is an array that contains the video's url.
The videos are downloaded on Downloads folder, but I have this problem : for a moment I downloaded 2 videos : first video has duration 1:17 and second video has duration 2:38. If I open first video it plays for 10 seconds and after that it close unexpectedly. The second video doesn't have this problem, it works fine. Do you have any idea why I have this problem ?
Any idea is welcome. Thanks in advance.