This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
File download with android
How do I download a .txt file from the internet at a given URL and save it to the phone in Android? It can be saved to either internal storage, SD storage, or anywhere really accessible for the app to use.
The URL I have been using for testing with loading URL WebViews is http://base.google.com/base/products.txt
This should do the trick. It downloads the file to sdcard/Download/products.txt. You can change it below.
try {
URL url = new URL("http://base.google.com/base/products.txt");
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream is = url.openStream();
File testDirectory = new File(Environment.getExternalStorageDirectory() + "/Download");
if (!testDirectory.exists()) {
testDirectory.mkdir();
}
FileOutputStream fos = new FileOutputStream(testDirectory + "/products.txt");
byte data[] = new byte[1024];
long total = 0;
int count = 0;
while ((count = is.read(data)) != -1) {
total += count;
int progress_temp = (int) total * 100 / lenghtOfFile;
/*publishProgress("" + progress_temp); //only for asynctask
if (progress_temp % 10 == 0 && progress != progress_temp) {
progress = progress_temp;
}*/
fos.write(data, 0, count);
}
is.close();
fos.close();
} catch (Exception e) {
Log.e("ERROR DOWNLOADING", "Unable to download" + e.getMessage());
}
Related
I need to save sensitive files to a cached directory using the native Download Manager. A location that can not be discovered by the user. I can easily download to the user's external file system using DownloadManager.Request(). Although using setDestinationInExternalPublicDir(), or any other way to set destination, does not allow me to save to a cached directory. Am I missing something here?
The build in DownloadManager can not save files to internal directories. Only to external directories like the SD card and other public directories e.g. the video or photos folder.
You have to forget the Android build in Download manager and create your own manager. Then you can download to path: getCacheDir().getAbsolutePath();
Here is a sample code to download a file yourself without build-in manager
public String downloadFile(String fileURL, String fileName) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Log.d(TAG, "Downloading...");
try {
int lastDotPosition = fileName.lastIndexOf('/');
if( lastDotPosition > 0 ) {
String folder = fileName.substring(0, lastDotPosition);
File fDir = new File(folder);
fDir.mkdirs();
}
//Log.i(TAG, "URL: " + fileURL);
//Log.i(TAG, "File: " + fileName);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setReadTimeout(30000);
c.connect();
double fileSize = (double) c.getContentLength();
int counter = 0;
while ( (fileSize == -1) && (counter <=30)){
c.disconnect();
u = new URL(fileURL);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setReadTimeout(30000);
c.connect();
fileSize = (double) c.getContentLength();
counter++;
}
File fOutput = new File(fileName);
if (fOutput.exists())
fOutput.delete();
BufferedOutputStream f = new BufferedOutputStream(new FileOutputStream(fOutput));
InputStream in = c.getInputStream();
byte[] buffer = new byte[8192];
int len1 = 0;
int downloadedData = 0;
while ((len1 = in.read(buffer)) > 0) {
downloadedData += len1;
f.write(buffer, 0, len1);
}
Log.d(TAG, "Finished");
f.close();
return fileName;
}
catch (Exception e) {
e.printStackTrace();
Log.e(TAG, e.toString());
return null;
}
}
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.
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.
In my app, I have requirement to download mp3 files from url. I am downloading file using Async Task. For testing purpose, I have kept file in dropbox. The problem is, it is not downloading complete file. The actual file size is of 5 MB. But, it is downloading only 29 KB of data. When I checked the length of content, it showed -1. I am not getting where is the problem. Below, I am posting my code.
#Override
protected Void doInBackground(String... sUrl)
{
InputStream input = null;
OutputStream output = null;
try
{
URL link = new URL(sUrl[0]);
HttpURLConnection urlConnection = (HttpURLConnection)link.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
int fileLength = urlConnection.getContentLength();
Log.v("Download file length", ""+fileLength);
input = urlConnection.getInputStream();
int downloadedSize = 0;
output = new FileOutputStream(Environment.getExternalStorageDirectory()
.getAbsolutePath()+"/audiofolder/1.mp3.mp3");
byte[] data = new byte[1024];
int bufferLength = 0;
while (((bufferLength = input.read(data)) > 0))
{
output.write(data, 0, bufferLength);
downloadedSize += bufferLength;
publishProgress((int)((downloadedSize/fileLength) * 100));
}//while
output.flush();
output.close();
input.close();
}//try
catch (MalformedURLException e)
{
e.printStackTrace();
}//catch
catch (IOException e)
{
e.printStackTrace();
}//catch
return null;
}//diInBackground
in My Application the Below Code Works Perfectly. you can try this Out.
#Override
protected Void doInBackground(String... aurl) {
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
File file = new File("mnt/sdcard/");
file.mkdirs();
File outputfile = new File(file, title + ".mp3");
FileOutputStream fileOutput = new FileOutputStream(outputfile);
InputStream inputStream = conexion.getInputStream();
int totalSize = conexion.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) != -1) {
downloadedSize += bufferLength;
onProgressUpdate((int) ((downloadedSize * 100) / totalSize));
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (Exception e) {
download = true;
e.printStackTrace();
}
return null;
}
Check your link.
When you see length of content = -1, it mean there is no length of content in header of link. It don't force under your download progress.
You only download 29KB because it download website, .html not file mp3.
Yout can copy and paste your link on brower to check.
From Android Documentation:
https://developer.android.com/reference/java/net/URLConnection.html#getContentLength()
getContentLength returns:
the content length of the resource that this connection's URL references, -1 if the content length is not known, or if the content length is greater than Integer.MAX_VALUE.
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.