I want to download a text file from a web url and save it locally on the device and use it in my application.
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 comes with getFilesDir() , assuming it always exists. However, there are a few issues with proper network connectivity and permissions:
- Is my assumption about
getFilesDir() anyway? - Are there any cases when the file is not uploaded / wrong content, etc., using this code?
- As soon as I ran into a problem when the file is uploaded but has all the encoded characters, no matter how I can download it, it still had the same encoded text. Only when I reinstall my application, then the correct text was downloaded. And since then this question has not been received. Any reason for this weird behavior?
EDIT: This is what I get as content when I try to read the file I downloaded (sometimes, 1 out of 10) shown in the logarithm:

Code for reading a 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();
thanks
source share