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.
Related
I developing an Android app on Android Studio.
I added a few files on Assets folder and my goal is the user through a button press to save them on his device.
I managed to find a way to do that but I have a problem!
After the first installation the app runs perfectly!
When I uninstalled it and reinstalled it the files were failing to be saved!
As you can see on my code, the folder that I am saving the files is the "/Documents".
I tried to change this location on my code and install the app again. Same results!!
It runs for the first time but when I am unistall it and reinstall it (with no changes on my code) I am getting the "Failed!" message as you can see on my code!
Do you guys have any idea what am I missing here?
Thanks!!
public class GKL10_pre extends AppCompatActivity {
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gkl10_pre);
button = (Button) findViewById(R.id.B_GKL10_FILES);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
copyAsset("file1.pdf");
copyAsset("file2.pdf");
copyAsset("file3.pdf");
copyAsset("file4.pdf");
}
});
}
private void copyAsset(String filename){
String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Documents";
File dir = new File(dirPath);
if(!dir.exists()) {
dir.mkdirs();
}
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(dirPath, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
Toast.makeText(this, "Saved!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Failed!", Toast.LENGTH_SHORT).show();
} finally {
if(in != null){
try {
in.close();
} catch (IOException e){
e.printStackTrace();
}
}
if(out != null){
try {
out.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
}```
The copy after reinstall fails as your files are still in Document directory but are not owned by the new install. So your app has no read an write access for those files.
You blindly try to overwrite them but that will not go lacking write access.
Try File.exists(), File.canRead and File.canWrite().
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);
I have wrote this code for download pdf from url and file url is this-
String fileURL= "http://www.vivekananda.net/PDFBooks/History_of_India.pdf";
Code this
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(true);
c.getResponseCode();
c.connect();
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) {
e.printStackTrace();
}
}
but this shows file not found exception with response code 405.I dont know why this happened.Please help..!!
This is my code where i had create file in sd card-
Code this
public void createPdfFile(){
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
File folder = new File(extStorageDirectory, "pdf");
folder.mkdir();
file = new File(folder, "storrage_data.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
}`
After this i am calling download method in thread like this from onResume(); beacuse from onCreate it will give error "Network On Main Thread".where i am wrong now i don't konw :(
Code this
public void downloadFile(){
new Thread(new Runnable() {
#Override
public void run() {
Downloader.DownloadFile(url, file);
showPdf();
}
}).start();
}
The possible reason is the folder in which you want to does not exist. First check if it exist. Create it if not. Then create fileoutputstream and write to it.
I suggest you use the DownloadManager. There are too many problems that can arise during download to handle all of them yourself. Just think of temporary loss of connectivity in the middle of download...
Below is some code I pulled out of my app and slightly modified to get rid of parts you don't need.
public void downloadAndOpenPdf(String url,final File file) {
if(!file.isFile()) {
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request req = new DownloadManager.Request(Uri.parse(url));
req.setDestinationUri(Uri.fromFile(file));
req.setTitle("Some title");
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
unregisterReceiver(this);
if (file.exists()) {
openPdfDocument(file);
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
dm.enqueue(req);
Toast.makeText(this, "Download started", Toast.LENGTH_SHORT).show();
}
else {
openPdfDocument(file);
}
}
public boolean openPdfDocument(File file) {
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
try {
startActivity(target);
return true;
} catch (ActivityNotFoundException e) {
Toast.makeText(this,"No PDF reader found",Toast.LENGTH_LONG).show();
return false;
}
}
Your code is correct. Now you need to download your pdf file to External storage or wherever you want to download and save it.
Delete this code and try again.
//c.setRequestMethod("GET");
//c.setDoOutput(true);
//c.getResponseCode();
//c.connect();
I think URL.openConnection() has description of connection already, so c.connect() isn't necessary.
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();