Housefly Housefly - 5 months ago 9
Android Question

Dowloading a text file from web

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:


  1. Does my assumption of
    getFilesDir()
    fail in any case?

  2. Are there any cases of either file not downloaded/wrong content etc.., with this code?

  3. 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:

enter image description here

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

Answer

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);
Comments