my code works fine, it downloads image to sd card, however , i get this warning where i defined my sd card path "Do not hardcode "/sdcard/"; use Environment.getExternalStorageDirectory().getPath() instead"
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/.temp");//.temp is the image file name
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
}
the problem is, if i use the suggested solution, then i won't be able to give my downloaded file a new name (".temp")
When working with files and directories, it's better to work with File objects rather than with strings. Here's how you can address the warning:
File dir = Environment.getExternalStorageDirectory();
File tmpFile = new File(dir, ".temp");
OutputStream output = new FileOutputStream(tmpFile);
That creates a File object that points to a file named ".temp" in the environment's external storage directory. It then opens it for writing using a different constructor of the FileOutputStream class.
If you need the file path as a string instead (say, for printing), you can do that too:
String tmpFileString = tmpFile.getPath();
Or if you decide to use the java.nio API in the future and need a Path object:
Path tmpFilePath = tmpFile.toPath();
Related
I'm trying to download files from Firebase storage. But when I download it, it's giving some files with .bin extension. But I want to get the original file name.
Here is my code.
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),
8192);
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+"/Download/"+ URLUtil.guessFileName(f_url[0], null, null));
Log.i("File name",URLUtil.guessFileName(f_url[0], null, null));
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
In there f_url is the firebase download url. Thank you.
The built in way of doing this is actually quite straightforward:
StorageReference reference = storage.getReferenceFromUrl("https://firebasestorage.googleapis.com/...");
// Assuming that the file is "name.extension" in Storage
String name = reference.getName().split(".")[0]
String extension = reference.getName().split(".")[1]
File localFile = File.createTempFile(name, extension);
reference.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
// Local temp file has been created
}
});
But if you don't want to do it the easy way...
Let's take a brief look at how you're naming your file: URLUtil.guessFileName(f_url[0], null, null)
According to the URLUtil.guessFileName() docs: "Guesses canonical filename that a download would have, using the URL and contentDisposition. File extension, if not defined, is added based on the mimetype."
I'm assuming that your f_url[0] is a file with no extension, and since you provide no contentDisposition or mimetype as arguments to guessFileName, there's no way it can possibly know what file extension you want.
You can get the contentDisposition and contentType (same as mimetype) from Storage Metadata, and if you name your file in Storage with an extension, you should be good to go.
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 have installed an Android app on my phone which I have created myself on java. The App got successfully installed on the device but I am not able to locate the package where it has installed.It is not located on the /data/data/my.package.com directory as well, There is no any directory created for my package name at data folder.
How to find the path of the installed application Please help?
And I download some image files form server. I want them to put them in to /data/data/my.package.com folder for delete when app uninstall.
Here is my downloading code.
private class DownloadImage extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/fog/images");
// Make sure the Pictures directory exists.
dir.mkdirs();
File destinationFile = new File(dir, "fog"+params[1]);
String filepath = null;
try{
URL url = new URL("http://admin.mindshaperapp.com/uploads/"+params[0]+".jpg");
HttpURLConnection conection = (HttpURLConnection)url.openConnection();
conection.setRequestMethod("GET");
conection.setRequestProperty("Content-length", "0");
conection.setUseCaches(false);
conection.setAllowUserInteraction(false);
conection.setConnectTimeout(15000);
conection.setReadTimeout(15000);
conection.connect();
int status = conection.getResponseCode();
switch (status) {
case 200:
case 201:
FileOutputStream fileOutput = new FileOutputStream(destinationFile);
InputStream inputStream = conection.getInputStream();
int totalSize = conection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 )
{
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
fileOutput.close();
if(downloadedSize==totalSize) filepath = destinationFile.getPath();
return filepath;
}
} catch (IOException e) {
}
return null;
}
}
I want to locate all images and application, the place where delete all things automatically when uninstall the application. please help
In your code, you're explicitly accessing the external storage; you'd want to access internal storage. To do that, change:
File sdCard = Environment.getExternalStorageDirectory();
to
File sdCard = Environment.getFilesDir();
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.