Download a text file from the Internet

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:

enter image description here

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

+6
source share
5 answers

Is my guess getFilesDir () anyway?

According to the documentation, it should always work without any permissions.

Are there any cases when the file is not uploaded / wrong content, etc. with this code?

Of course, I mean that just going through the connection will cause the download to fail, and many other things can go wrong like skipping the required permission (android.permission.INTERNET), incorrect encoding, full disk, ...

As soon as I ran into a problem when the file is uploaded, but all the characters are encoded, no matter how I download it, it still had the same encoded text. Only when I reinstall my application, then the text was downloaded. And since then this question has not been received. Any reason for this weird behavior?

Perhaps this was an encoding problem, wrap the FileOutputStream file in OutputStreamWriter , which allows you to pass the encoding parameter in the constructor.

 Writer writer = new OutputStreamWriter(fos); . . . writer.write(buffer, 0, length); 
+2
source

The following example might be useful:

 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) { } 
+1
source

This is not an answer, but a tip, use the ion network library for Android.

From the 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 not performed in the user interface thread, so the user always sees a responsive application.

0
source

I cannot comment on what goes wrong in your case, I will post a piece of code that I use to determine what type of file I am targeting and then get it. It always worked as expected for me. I changed the "onPostExecute" method according to my answer here, and I tried to keep my variable names similar to yours. To simplify the fragment, I omitted the download progress bar. Downloading should be done in the background, so "AsyncTask" is used. For the snippet, I use a 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(); 
0
source

Try using the code below:

 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; } } 
0
source

Source: https://habr.com/ru/post/977754/


All Articles