I want to download a text file from a web url and save it locally on the device and use it in my app.
Code:
try {
File file = new File(getFilesDir(), "file.txt");
if (file.length() > 0) {
//File already exists and it is not empty
return;
}
URL url = new URL("https://www.abc.com/file.txt");
FileOutputStream fos = new FileOutputStream(file);
InputStream in = url.openStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = in.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fos.flush();
fos.close();
} catch (Exception e) {
// TODO:
}
As you can see, the code goes with getFilesDir() assuming that always exists. However there are few questions, with proper network connection and permissions:
Does my assumption of getFilesDir() fail in any case?
Are there any cases of either file not downloaded/wrong content etc.., with this code?
Once I faced an issue where the file is downloaded but has all encoded characters, no matter how may times I downloaded it, it still had the same encoded text. Only when I re-installer my app, then the proper text was downloaded. And never got that issue ever since. Any reason for that weird behavior?
EDIT:
Here is what I get as the content when I try to read the file which I downloaded(happens sometimes, 1 in 10) shown in the logcat:
Code to read the file:
BufferedReader inputReader= = new BufferedReader(
new InputStreamReader(new FileInputStream(file)));
String inputString;
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null) {
Log.e("inputString: ", inputString);
}
inputReader.close();
Thank You
Does my assumption of getFilesDir() fail in any case?
According to the documentation it should always work with no permissions required.
Are there any cases of either file not downloaded/wrong content etc..,
with this code?
Sure, I mean just a simple connection drop will cause download failure and so many other things can go wrong like missing required permission (android.permission.INTERNET), wrong encoding, disk full, ...
Once I faced an issue where the file is downloaded but has all encoded
characters, no matter how may times I downloaded it, it still had the
same encoded text. Only when I re-installer my app, then the proper
text was downloaded. And never got that issue ever since. Any reason
for that weird behavior?
It might have been an encoding issue, wrap your FileOutputStream in an OutputStreamWriter, which allows you to pass encoding parameter in the constructor.
Writer writer = new OutputStreamWriter(fos);
.
.
.
writer.write(buffer, 0, length);
The following example may be helpful:
try {
// Create a URL for the desired page
URL url = new URL("mysite.com/thefile.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
That's not really an answer but an advice, use ion a networking library for Android.
From examples:
Ion.with(context)
.load("http://example.com/really-big-file.zip")
// have a ProgressBar get updated automatically with the percent
.progressBar(progressBar)
// and a ProgressDialog
.progressDialog(progressDialog)
// can also use a custom callback
.progress(new ProgressCallback() {#Override
public void onProgress(int downloaded, int total) {
System.out.println("" + downloaded + " / " + total);
}
})
.write(new File("/sdcard/really-big-file.zip"))
.setCallback(new FutureCallback<File>() {
#Override
public void onCompleted(Exception e, File file) {
// download done...
// do stuff with the File or error
}
});
All operations are done not in the UI thread, so the user always see a responsive app.
Try with below code:
public void downloadFile(){
String DownloadUrl = "Paste Url to download a text file hereā¦";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadUrl));
request.setDescription("sample text file for testing"); //appears the same in Notification bar while downloading
request.setTitle("Sample.txt");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalFilesDir(getApplicationContext(),null, "sample.pdf");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
public static boolean isDownloadManagerAvailable(Context context) {
try {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
return false;
}
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClassName("com.android.providers.downloads.ui","com.android.providers.downloads.ui.DownloadList");
List <resolveinfo> list = context.getPackageManager().queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
} catch (Exception e) {
return false;
}
}
I cannot really comment on what goes wrong in your case, I will post a snippet of a code I'm using to detect what type of file I'm targeting and then get it. This has always worked as expected for me. I've modified my "onPostExecute" method to suit my answer here and I've tried to keep the names of my variables similar to yours. I've omitted the download progress indication bar to simplify the snippet. The download has to be done in the background, therefore "AsyncTask" is used. For the snippet I use random text file from google.
final String file_url = "https://www.kernel.org/doc/Documentation/power/drivers-testing.txt";
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(file_url);
final String fileName = URLUtil.guessFileName(file_url, null, fileExtension);
final String path = Environment.getExternalStorageDirectory().toString() + "/" + fileName;
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL(file_url);
URLConnection connection = url.openConnection();
connection.connect();
// download the file
InputStream in = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(path);
byte buffer[] = new byte[1024];
int length;
while ((length = in.read(buffer)) != -1) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
in.close();
} catch (IOException e) {
Log.e("Downloading file", "Download Error", e);
}
return null;
}
#Override
public void onPostExecute(Void result) {
try {
File file = new File(path);
BufferedReader inputReader = new BufferedReader(new FileReader(file));
String inputString;
while ((inputString = inputReader.readLine()) != null) {
Log.e("inputString: ", inputString);
}
inputReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.execute();
Related
I have webview which we have php application loaded. the application lists item which the user selects. when a list is selected. it does a redirect with a file path from the server which is captured using the below code.
1.get the file name and extension from the url and use it too create a new file which we will use it for writing outputstream to it.
2. call the downloadFile() method to read the file
3. call the ShoWeDrawings() passing the filename to use it to read the file and pass it to open it using intent action_view with another app.
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// This is my web site, so do not override; let my WebView load the page
if(url.contains("Files") ) {
String filename = url.substring(url.lastIndexOf('/') +1);
String extStorageDirectory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/EASM";
File folder = new File(extStorageDirectory);
if (!folder.exists()) {
folder.mkdir();
}
File file = new File(folder, filename);
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile( url,file);
ShoWeDrawings(filename);
return true;
}
return false;
}
download class
public class Downloader {
private static Context context;
// public Context context ;
public static void DownloadFile(String fileURL, File directory){
try{
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(false);
c.setConnectTimeout(10000);
c.setReadTimeout(10000);
c.connect();
int status = c.getResponseCode();
// InputStream in = c.getErrorStream();
InputStream in = c.getInputStream();
// c.getErrorStream();
byte[] buffer = new byte[4096];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
in.close();
// Toast.makeText(context.getApplicationContext(), "A new file is downloaded successfully", Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
ShoWeDrawings method
private void ShoWeDrawings(String filename) {
File file = new File( getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+"/EASM/"+filename);
// Uri uri = Uri.fromFile(file);
try {
Intent mIntent = new Intent(Intent.ACTION_VIEW);
// mIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Uri.fromFile(file));
// mIntent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(file));
mIntent.setDataAndType(Uri.fromFile(file), "application/octet-stream");
mIntent.setPackage("com.solidworks.eDrawingsAndroid");
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Intent.createChooser(mIntent, "Choose Application");
startActivity(mIntent);
}
catch (Exception e)
{
e.printStackTrace();
}
}
now the problem comes with the opening of the file using the targeted app. i get a toast error message. Im not sure if its due to permissions or its the app that has problems. By the way i have upgraded to android 11 and i cant even view data/ folder on the tablet. i can only see the files via pc. The error message that im getting is - filename:error copying file to documents folder see picture below.
I tried to change the code and restarting the tablet thinking it might have been the updates that i pushed.
I used the code below in executor service to download a file from URL. It downloads the file but size is 0 bytes. code works fine when I use asyncTask. but when I put it in executor service doesn't work.
Any ideas why the download won't be complete?
onCreate:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ExecutorService pool = Executors.newSingleThreadExecutor();
Button btn = findViewById(R.id.btn);
String url = "https://file-examples-com.github.io/uploads/2017/10/file_example_JPG_100kB.jpg";
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pool.execute(new NetworkService(url));
}
});
NetworkService class:
private class NetworkService implements Runnable {
private String url;
public NetworkService(String url) {
this.url = url;
}
#Override
public void run() {
dlFile(url);
}
private String dlFile(String surl) {
try {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(surl);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
return "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage();
input = connection.getInputStream();
String title = URLUtil.guessFileName(String.valueOf(url), null, null);
output = new FileOutputStream(Environment.getExternalStorageDirectory().toString() + "/" + title);
} 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();
}
} finally {
}
return null;
}
}
There are a couple of things you should do and verify.
1 - First of all, make sure you have granted the required permissions to save file to the storage.
READ_EXTERNAL_STORAGE
WRITE_EXTERNAL_STORAGE
INTERNET
2 - Add android:requestLegacyExternalStorage="true" to your manifest file's application tag for android 10 and later versions.
3 - Correct your FileOutputStream initialisation, because
val direct = File(Environment.getExternalStorageDirectory().toString() + "/test_files")
You are creating a path above in test_files Folder, but in FileOutputStream you have specified different path. So, the correct line should be
output = FileOutputStream( direct + "/" + title)
And finally, add the following line after output = line to write image to the buffer, because you are reading the InputStream but you are not writing it on the buffer. That is why, it only create the path in storage, but do not write file to that path.
val buf = ByteArray(1024)
var len: Int
while (input.read(buf).also { len = it } > 0) {
output.write(buf, 0, len)
}
PS: I have written the code in Kotlin and tested it on Android 10, It works fine.
I hope this helps. Please don't forget to accept the answer if it help.
I'm running an Android application and I want to load a font dynamically and use it during runtime. How can I do this?
And also how can I include a font in an SDK that I've written, reference the sdk in the app I've written, and use the font included in the SDK?
Edit: Thanks for putting a -1 Vote on this, whoever did this, I'll stop sharing knowledge, that's a good way to shut me down.
Here's how I would do it: (Using an AsyncTask, which is not perfect)
If you want something more stable than an AsyncTask RxAndroid offers other good variants, far more stable.
In this example I'm doing everything in the "doInBackground" section, but you can use it the same way, anywhere after the task is done.
This example also assumes we have persmissions to write and read from external storage.
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
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.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();
}
// download the file
input = connection.getInputStream();
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/fonts");
dir.mkdirs();
File file = new File(dir, "font.ttf");
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while((len=input.read(buf))>0){
out.write(buf,0,len);
}
out.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
File sdcard = Environment.getExternalStorageDirectory();
File dirs = new File(sdcard.getAbsolutePath()+"/fonts");
if(dirs.exists()) {
File[] files = dirs.listFiles();
Log.d("s","files");
}
final Typeface typeface = Typeface.createFromFile(
new File(Environment.getExternalStorageDirectory()+"/fonts", "font.ttf"));
Log.d("a","created");
// Now I'm starting with an example that shows how to use
// this font on a textview of my choice.
// Assumptions: font has characters uF102 and uF104
final TextView tv = (TextView) findViewById(R.id.myTextView);
runOnUiThread(new Runnable() {
#Override
public void run() {
if (tv != null && typeface != null) {
tv.setTypeface(typeface);
tv.setText("\uF102");
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (tv.getText().equals("\uF102")){
tv.setText("\uF104");
} else {
tv.setText("\uF102");
}
}
});
}
}
});
} 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;
}
}
In case we want to load the font from an sdk we're using, of from a library we've written, we can include the font in the drawable raw section, and from the application using this sdk/lib we can reference the font like so:
(I've used the amaticobold font in this case just for example)
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/fonts");
dir.mkdirs();
File file = new File(dir, "font.ttf");
InputStream is = getResources().openRawResource(getResources().getIdentifier("amaticbold","raw", getPackageName()));
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while((len=is.read(buf))>0){
out.write(buf,0,len);
}
out.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
File sdcard = Environment.getExternalStorageDirectory();
File dirs = new File(sdcard.getAbsolutePath()+"/fonts");
if(dirs.exists()) {
File[] files = dirs.listFiles();
Log.d("s","files");
}
final Typeface typeface = Typeface.createFromFile(
new File(Environment.getExternalStorageDirectory()+"/fonts", "font.ttf"));
editText.setTypeface(typeface);
Has anyone been able to use PersistableDownload on AWS Android SDK? I've been trying to use it to resume downloads when the App crashes, but with no success so far. I don't think I'm getting the concept serialize/deserialize right. Here is the code I got so far:
AmazonS3Client s3Client = getAmazonS3Client(Regions.SA_EAST_1);
TransferManager tx = new TransferManager(s3Client);
String bucket = "MyBucket";
String key = "IMG_20140915_132548.jpg";
String[] parts = key.split("/");
String fileName = parts[parts.length - 1];
final String full_path = "/storage/sdcard0/" + fileName;
File file = new File(full_path);
FileInputStream fis = null;
if(file.exists()) {
try {
fis = new FileInputStream(file);
PersistableDownload persistableUpload = PersistableTransfer.deserializeFrom(fis);
Download meuDown = tx.resumeDownload(persistableUpload);
} catch (Exception e1) {
e1.printStackTrace();
}
}
else {
GetObjectRequest getRequest = new GetObjectRequest(bucket, "IMG_20140915_132548.jpg");
Download download = tx.download(getRequest, file, new S3ProgressListener() {
#Override
public void progressChanged(ProgressEvent arg0) {
long transferred = arg0.getBytesTransferred();
Log.d("AWS3", "" + transferred);
}
#Override
public void onPersistableTransfer(PersistableTransfer arg0) {
Log.d("AWS3", "Writing to file");
File f = new File("/storage/sdcard0/resume-upload");
FileOutputStream fos;
try {
if (f.exists() == false)
f.createNewFile();
fos = new FileOutputStream(f);
arg0.serialize(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
I noticed that the onPersistableTransfer method is only called once, so I don't know how all the received bytes are serialized to the disk.
Any advices on how to get PersistableDownload to work? I'm using the SDK 2.1, with a real cell phone (Android 4.4.4) and Eclipse.
From the above code, I see that you are passing the partially downloaded image file to resume the download process.
if(file.exists()) {
try {
fis = new FileInputStream(file);
PersistableDownload persistableUpload = PersistableTransfer.deserializeFrom(fis);
Download meuDown = tx.resumeDownload(persistableUpload);
} catch (Exception e1) {
e1.printStackTrace();
}
}
Here file is referring to the partially downloaded image file. You will need to pass the file "/storage/sdcard0/resume-upload" to resume the upload.
I'm trying to implement a Class that is downloading a HTML-File and save this locally on my device. When the HTML-File changes I want to redownload the HTML-File and overwrite the existing one. After this I want to pass this HTML-File to Jsoup to work with it. However my Class is not working. The following Code gives me a "java.io.FileNotFoundException:/tabelle.html: open failed: ENOENT (No such file or directory)"
So rather my download isn't working at all or I have some missleading paths in my Code. Hope someone can help me ...
public class DownloadData extends AsyncTask<String, Void, Boolean> {
private ProgressBar pBar;
InputStream is;
BufferedInputStream bis;
ByteArrayBuffer baf;
FileOutputStream fos;
protected void onPreExecute() {
pBar = (ProgressBar)findViewById(R.id.progressBar2);
pBar.setVisibility(View.VISIBLE);
}
protected Boolean doInBackground(String... website) {
try {
URL url = new URL(website[0]);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
long dateHttp = urlConnection.getLastModified();
File file = new File("tabelle.html");
long dateLocal = file.lastModified();
if(dateLocal < dateHttp || file.exists() == false) {
is = urlConnection.getInputStream();
bis = new BufferedInputStream(is);
baf = new ByteArrayBuffer(1024);
int current = 0;
while((current = bis.read()) != -1) {
baf.append((byte) current);
}
fos = openFileOutput("tabelle.html", Context.MODE_PRIVATE);
fos.write(baf.toByteArray());
return true;
}
else {
return false;
}
}
catch (Exception e) {
return false;
}
finally {
try {
is.close();
bis.close();
baf.clear();
fos.close();
}
catch(Exception e) {
return false;
}
}
}
protected void onPostExecute(Boolean result) {
pBar.setVisibility(View.GONE);
try {
File file = new File("tabelle.html");
Document doc = Jsoup.parse(file, "CP1252", "");
}
catch(Exception e) {
((TextView)findViewById(R.id.textViewC4)).setText(e.toString());
}
}
}
The error is in this line new File("tabelle.html"); it is creating a File in the Linux root partition, and that is a system exclusive area. Check on [THIS LINK][1] the proper way to access files in the disk on Android.
Remember that if you're going to use external storage (for your use-case I don't think you should) you need the WRITE_EXTERNAL_STORAGE permission.
edit:
I noticed that you're writing to the file using openFileOutput(). That is a different location than when you create using new File()
as mentioned by #hgoebl, to get a file in the same location as openFileOutput() you should use new File(getCacheDir(), "filename"); (or maybe getDir()) I honestly don't remember and you'll have to test it.