Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to download a file using a download_url but actually it's not the download link
When I hit the download_url Actual file download starts which actually contains filename and extension
Now I want to discover filename and extension
I've tried this
FilenameUtils.getExtension(download_url);
FilenameUtils.getName(download_url)
And also this
URLUtil.guessFileName(download_url, null, null);
But I'm getting an empty string, how to find filename and extension?
Check the codes in the below that download PDF File and Open Directly in PDF Viewer:
downloadButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String URL = "www.XXXXX.com";
if (NetworkUtil.isConnectingToInternet(getActivity())) {
downloadPDFAsyncTask pdfAsyncTask = new downloadPDFAsyncTask();
pdfAsyncTask.execute();
} else {
NetworkUtil.showDialog(getActivity(),
R.string.internetTitle,
R.string.internetMessage);
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private class downloadPDFAsyncTask extends
AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
NetworkUtil.showProgressDialog(getActivity());
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(String... aurl) {
try {
System.out.println("URL >>>>> " + URL);
URL url = new URL(URL);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
// connect
urlConnection.connect();
checkAndCreateDirectory("/fileDirectory");
file = new File(rootDir, "fileDirectory");
System.out.println("file >>>>> " + file);
FileOutputStream fileOutput = new FileOutputStream(file);
// Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
// this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
System.out.println("totalSize >>>>> " + totalSize);
// create a buffer...
byte[] buffer = new byte[1024 * 1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
// close the output stream when complete //
fileOutput.close();
} catch (final MalformedURLException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
} catch (final Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String unused) {
super.onPostExecute(unused);
try {
NetworkUtil.hideProgressDialog(getActivity());
PackageManager packageManager = getActivity()
.getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List<?> list = packageManager.queryIntentActivities(testIntent,
PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0 && file.isFile()) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
} else {
NetworkUtil
.showDialog2(getActivity(), "Error",
"PDF Reader application is not installed in your device");
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// function to verify if directory exists
public void checkAndCreateDirectory(String dirName) {
File new_dir = new File(rootDir + dirName);
if (!new_dir.exists()) {
new_dir.mkdirs();
}
}
Related
I am trying to download a pdf file from the url using onNext() of Rxjava2. After downloading and storing the file in the folder, I have written the code logic in the oncomplete() to open up the pdfview through intents to show up the pdf to the user. But the onComplete() never gets called. Have used breakpoints as well to check but the compiler doesnt never executes the onComplete().
MainActivity:
home_quarantine_guidelines.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
observable = Observable.just
("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf");
observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DisposableObserver<String>() {
#Override
public void onNext(String s) {
//customProgressDialog.show();
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "Intelehealth_COVID_PDF");
folder.mkdir();
File pdfFile = new File(folder, "dummy.pdf");
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(s, pdfFile);
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
customProgressDialog.dismiss();
File pdfFile = new File
(Environment.getExternalStorageDirectory()
+ "/Intelehealth_COVID_PDF/" + "dummy.pdf");
Uri path = FileProvider.getUriForFile
(context, context.getApplicationContext().getPackageName()
+ ".provider", pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
pdfIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
try{
startActivity(pdfIntent);
}catch(ActivityNotFoundException e){
Toast.makeText(HomeActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
}
});
// File pdfFile_downloaded = new File(Environment.getExternalStorageDirectory() + "/Intelehealth_COVID_PDF/" + "dummy.pdf");
//
// if(pdfFile_downloaded.exists())
// {
// File pdfFile = new File(Environment.getExternalStorageDirectory() + "/Intelehealth_COVID_PDF/" + "dummy.pdf"); // -> filename = maven.pdf
// //Uri path = Uri.fromFile(pdfFile);
// Uri path = FileProvider.getUriForFile
// (context, context.getApplicationContext().getPackageName()
// + ".provider", pdfFile);
// Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
// pdfIntent.setDataAndType(path, "application/pdf");
// pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// pdfIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// pdfIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
//
// try{
// startActivity(pdfIntent);
// }catch(ActivityNotFoundException e){
// Toast.makeText(HomeActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
// }
// }
// else
// {
// customProgressDialog.show();
// new DownloadFile().execute("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf", "dummy.pdf");
// }
}
});
FileDownloaded.class:
public class FileDownloader extends FileProvider {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
// urlConnection.setRequestMethod("GET");
// urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer)) > 0){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
EDIT: When I use AsyncTask, the code executes correctly. But why does
it not execute/work using RxJava2 ?
From the hint given by #EpicPandaForce in his comment, I figured out the issue. I was using create operator of Rxjava to emit a single item. Due to which it was never reaching the onComplete(). With the given hint and referring the documentation, I realized that I have to use Single.fromCallable() as I wanted to emit a single thread.
Code:
Single.fromCallable(() ->
{
String s = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "Intelehealth_COVID_PDF");
folder.mkdir();
File pdfFile = new File(folder, "dummy.pdf");
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(s, pdfFile);
return s;
})
.subscribeOn(Schedulers.io())
.subscribe(new SingleObserver<String>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onSuccess(String s) {
File pdfFile = new File
(Environment.getExternalStorageDirectory()
+ "/Intelehealth_COVID_PDF/" + "dummy.pdf");
Uri path = FileProvider.getUriForFile
(context, context.getApplicationContext().getPackageName()
+ ".provider", pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
pdfIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
try{
startActivity(pdfIntent);
}catch(ActivityNotFoundException e){
Toast.makeText(HomeActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onError(Throwable e) {
}
});
I want to download this pdf file
https://scholar.najah.edu/sites/default/files/book/dllt-lhwy-wlrmz-fy-lfwlklwr-lshby.pdf
I am using this code to download pdf files, it works fine with many files but it failed on pdf file like above
public void downloadFile(#NonNull String urlStr, #NonNull String fullFilePath,
#NonNull DownloadListener downloadListener) {
cancelStatus = false;
InputStream is = null;
File ffPath = null;
FileOutputStream fos = null;
try {
downloadListener.onProgress(0);
URL url = new URL(urlStr);
URLConnection conexion = url.openConnection();
conexion.setReadTimeout(2000000);
conexion.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.0 Safari/532.5");
System.setProperty("http.agent", "");
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
if (lenghtOfFile <= 0) lenghtOfFile = 1;
is = url.openStream();
ffPath = new File(fullFilePath);
fos = new FileOutputStream(ffPath);
int count = 0;
long total = 0;
int progress = 0;
byte data[] = new byte[1024];
while ((count = is.read(data)) != -1) {
if (cancelStatus == true) {
break;
}
total += count;
int progress_temp = (int) total * 100 / lenghtOfFile;
if (progress != progress_temp) {
progress = progress_temp;
downloadListener.onProgress(progress >= 0 && progress <= 100 ? progress : 0);
}
fos.write(data, 0, count);
cancelStatus = downloadListener.onPacketDownloaded(total, lenghtOfFile);
}
if (is != null) is.close();
if (fos != null) fos.close();
if (lenghtOfFile <= 1) {
downloadListener.onComplete();
} else if (ffPath.length() < lenghtOfFile) {
if (cancelStatus) {
downloadListener.onCancel();
} else {
downloadListener.onError();
}
} else if (ffPath.length() >= lenghtOfFile) {
downloadListener.onComplete();
}
if (cancelStatus == true) {
if (ffPath != null) ffPath.delete();
}
} catch (MalformedURLException e) {
try {
if (is != null) is.close();
if (fos != null) fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
if (ffPath != null) ffPath.delete();
downloadListener.onError();
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
try {
if (is != null) is.close();
if (fos != null) fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
if (ffPath != null) ffPath.delete();
downloadListener.onError();
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
try {
if (is != null) is.close();
if (fos != null) fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
if (ffPath != null) ffPath.delete();
downloadListener.onError();
// TODO Auto-generated catch block
e.printStackTrace();
}
}
the problem is count = is.read(data) return -1 and break from while loop after one loop, the file about 345 kb
please help
/**
* download file used too download the file and save into phone
*
* #param fileURL contain file url
* #param fileName contain file name
*/
public void DownloadFile(String fileURL, String fileName) {
try {
String RootDir = Environment.getExternalStorageDirectory()
+ File.separator + "Cards List";
File RootFile = new File(RootDir);
RootFile.mkdir();
// File root = Environment.getExternalStorageDirectory();
java.net.URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(RootFile,
fileName + " abc " + ".pdf"));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d("Error....", e.toString());
}
} // used to download the file from server
class ProgressBack extends AsyncTask<String, Void, Void> {
ProgressDialog PD;
#Override
protected void onPreExecute() {
super.onPreExecute();
PD = ProgressDialog.show(MainActivity.this, null, "Please Wait ...", true);
PD.setCancelable(true);
}
#Override
protected Void doInBackground(String... params) {
DownloadFile("https://scholar.najah.edu/sites/default/files/book/dllt-lhwy-wlrmz-fy-lfwlklwr-lshby.pdf",
"Cards List"); // calling DownloadFile
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
PD.dismiss();
Toast.makeText(MainActivity.this, "Download Completed", Toast.LENGTH_SHORT).show();
}
}
I want my program to download many images (around 500) from the internet and store them in my external storage. Currently when I download a single image, it shows a progressBar and downloads the image properly. However when I am trying to replicate w/ two images, it gives the Toast for "Download complete" for both images being downloaded, however no progressBar for either image is shown and only the first image is properly downloaded.
Here is the code for my onCreate method for activity.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove Title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//force portrait orientation. (No landscape orientation).
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_quran);
//Instantiate ProgressDialog (Used for downloading quran pages).
myProgressDialog = new ProgressDialog(QuranActivity.this);
myProgressDialog.setMessage("Downloading Quran");
myProgressDialog.setIndeterminate(true);
myProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
myProgressDialog.setCancelable(true);
//execute when the downloader must be fired.
final DownloadTask downloadTask = new DownloadTask(QuranActivity.this);
DownloadTask second = new DownloadTask(getApplicationContext());
myHTTPURL = "https://ia601608.us.archive.org/BookReader/BookReaderImages.php?zip=/10/items/05Quran15LineWhitePageWithVioletBorderWww.Momeen.blogspot.com/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2.zip&file=05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_0001.jp2&scale=1&rotate=0";
myHTTPURL2 = "https://ia601608.us.archive.org/BookReader/BookReaderImages.php?zip=/10/items/05Quran15LineWhitePageWithVioletBorderWww.Momeen.blogspot.com/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2.zip&file=05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_0002.jp2&scale=1&rotate=0";
//First check if the file has already been created. (Only need to download 1ce, or
//in the case where the user deleted the files, we reinstall them again).
if (isExternalStorageWritable()) {
File makeDirectory = getQuranStorageDir(QuranActivity.this, "Quran_Pages");
for (int i = 0; i < 2; i++) {
Bundle myBundle = new Bundle();
myBundle.putInt("i", i);
if (i == 0) {
downloadTask.execute(myHTTPURL);
try {
downloadTask.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
myProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
} else {
/*if (downloadTask.getStatus() == AsyncTask.Status.FINISHED) {
downloadTask.execute(myHTTPURL2);
} else if (downloadTask.getStatus() == AsyncTask.Status.RUNNING) {
try {
downloadTask.execute(myHTTPURL2).wait(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} */
second.execute(myHTTPURL2);
try {
second.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
// downloadTask.execute(myHTTPURL2);
}
}
}
and this is the code for my AsynTask Class.
#TargetApi(Build.VERSION_CODES.FROYO)
private class DownloadTask extends AsyncTask {
private Context context;
private PowerManager.WakeLock myWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("GET");
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
//Display download percentage.
int fileLength = connection.getContentLength();
//create folder to place the downloaded file in.
// File Path:E:\Android\data\com.syedabdullah.syed.quran_memorization_application
// \files\Quran Memorization Application\Quran_Pictures
//So first create a root folder Quran Memorization Application then inside that
//folder we create another folder named Quran Pictures.
/* File rootFolder = new File(getExternalFilesDir("Quran Memorization Application"),
"Quran_Pages"); */
//Here we insert inside the Quran_Pictures folder the quran_pages.
//String myFileName = "quran_01.jpg";
Bundle y = new Bundle();
int retrievePos = y.getInt("i");
String quranFilePageName = "_" + retrievePos + ".jpg";
// String fileName = "justwork.jpg";
File sup = new File(getExternalFilesDir("Quran Memorization Application"), "Quran_Pages");
File myFile = new File(sup, quranFilePageName);
myFile.createNewFile();
//downlaod the file.
input = connection.getInputStream();
output = new FileOutputStream(myFile);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
//allow cancel with back button.
if (isCancelled()) {
input.close();
return null;
}
total += count;
//publish the progress.
if (fileLength > 0) {
publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(myFile));
QuranActivity.this.sendBroadcast(intent);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
if (input != null) {
input.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (connection != null) {
connection.disconnect();
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//Take CPU lock to prevent CPU from going off if the user presses the power button.
//during download.
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
myWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
myWakeLock.acquire();
myProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
//If we get here length is known, so setIndertimante to false.
myProgressDialog.setIndeterminate(false);
myProgressDialog.setMax(100);
myProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
myWakeLock.release();
myProgressDialog.dismiss();
if (result != null) {
Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Download Complete", Toast.LENGTH_SHORT).show();
}
}
} }
I was hoping to have a for loop that would create hundreds of downloadTasks and download all the images I need, and then I would call the get method. However in order for that to work, I first need too know why when I try for 2 images only the first one gets downloaded and why no progressbar shows up. Also if possible if I could get a hint as to how I can make my progressBar update for all the images and not be designed for just 1. Thanks in advance. (Note all URLs are currect.)
Thank you so much! figured out that my loops were suppose to go inside doInBackground. Also to anyone else having a similar issue. To download multiple files and display a decent progressBar, here is a very great tutorial: http://theopentutorials.com/tutorials/android/dialog/android-download-multiple-files-showing-progress-bar/
I would like to download a large pdf file with jsoup. I have try to change timeout and maxBodySize but the largest file I could download was about 11MB. I think if there is any way to do something like buffering. Below is my code.
public class Download extends Activity {
static public String nextPage;
static public Response file;
static public Connection.Response res;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle b = new Bundle();
b = getIntent().getExtras();
nextPage = b.getString("key");
new Login().execute();
finish();
}
private class Login extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
res = Jsoup.connect("http://www.eclass.teikal.gr/eclass2/")
.ignoreContentType(true).userAgent("Mozilla/5.0")
.execute();
SharedPreferences pref = getSharedPreferences(
MainActivity.PREFS_NAME, MODE_PRIVATE);
String username1 = pref.getString(MainActivity.PREF_USERNAME,
null);
String password1 = pref.getString(MainActivity.PREF_PASSWORD,
null);
file = (Response) Jsoup
.connect("http://www.eclass.teikal.gr/eclass2/")
.ignoreContentType(true).userAgent("Mozilla/5.0")
.maxBodySize(1024*1024*10*2)
.timeout(70000*10)
.cookies(res.cookies()).data("uname", username1)
.data("pass", password1).data("next", nextPage)
.data("submit", "").method(Method.POST).execute();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
String name = "eclassTest.pdf";
FileOutputStream out;
try {
int len = file.bodyAsBytes().length;
out = new FileOutputStream(new File(PATH + name));
out.write(file.bodyAsBytes(),0,len);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I hope somebody could help me!
I think, it's better to download any binary file via HTTPConnection:
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL("http://example.com/file.pdf");
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();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[4096];
int count;
while ((count = input.read(data)) != -1) {
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();
}
Jsoup is for parsing and loading HTML pages, not binary files.
I hit to a URL where my apk file is hosted and then write the bytes received to a file.
class DownloadAPKFile extends AsyncTask<String, Void, Boolean>{
private byte[] fileBytes;
#Override
protected Boolean doInBackground(String... params) {
Log.d("begin", "begun");
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://www.website/Path/my.apk");
try {
HttpResponse response = client.execute(get);
Log.d("Login", "Response " + response.getEntity());
Log.d("Login", "contentLength " + response.getEntity().getContentLength());
String responseBody = EntityUtils.toString(response.getEntity());
fileBytes = responseBody.getBytes();
Log.d("fileBytes", "fileBytes");
String filePath = Environment.getExternalStorageDirectory() + "/myappdir/" + "my" + ".apk";
File file = new File(filePath);
file.getParentFile().mkdirs();
file.createNewFile();
BufferedOutputStream objectOut = new BufferedOutputStream(new FileOutputStream(file));
Log.d("objectOut", "objectOut");
objectOut.write(fileBytes);
Log.d("write", "write");
objectOut.close();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
This works like a charm, the problem i am having is that the content length from the entitiy is 582504 but when i look into the file manager the size goes upto 863145. I think that some data is being added while writing file to SD Card. Is there any solution to this?
This is my code which works fine, please check if this works for you
public class downloadApk extends AsyncTask<Integer, Integer, Integer>
{
#Override
protected Integer doInBackground(Integer... params) {
// TODO Auto-generated method stub
try {
URL url = new URL("http://www.tagsinfosoft.com/android/shelf/Shelf_Cam.apk");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "Shelf_Cam.apk");
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();//till here, it works fine - .apk is download to my sdcard in download file
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Context context=shelf.this;
pd.dismiss();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "Shelf_Cam.apk")), "application/vnd.android.package-archive");
startActivity(intent);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd=ProgressDialog.show(shelf.this,"Updating","Please wait....." );
}
}