To TheLimit
To TheLimit

Reputation: 31

Read file from internal storage

I have an AsyncTask to download a file to internal storage in my android app. I want to read this file later but I don´t know how can I do this. This is my AsyncTask´s code:

private class GetFile  extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(ComprobadorDos.this);
            pDialog.setMessage("Por favor espere...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {

            try {


                    File fileEvents = new File(context.getFilesDir().getAbsolutePath() + "/agenda_hoy.json");

                    if (fileEvents.exists()) {
                        fileEvents.delete();
                    }

                    String buffer;
                    URLConnection conn = new URL(CALLBACK_URL).openConnection();
                    conn.setUseCaches(false);
                    conn.connect();
                    InputStreamReader isr = new InputStreamReader(conn.getInputStream());
                    BufferedReader br = new BufferedReader(isr);

                    FileOutputStream fos = context.openFileOutput("agenda_hoy.json", Context.MODE_PRIVATE);

                    while ((buffer = br.readLine()) != null) {
                        fos.write(buffer.getBytes());
                    }

                    fos.close();
                    br.close();
                    isr.close();




            } catch (Exception e) {
                Log.d(LOG_TAG, e.getMessage());
            }

            return null;
        }


        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();

        }


    }

I hope this is a good code, if someone knows a better practice please tell me how can I do this.

Upvotes: 0

Views: 2791

Answers (1)

Apperside
Apperside

Reputation: 3602

    //Get the text file
    File fileEvents = new File(context.getFilesDir().getAbsolutePath() + "/agenda_hoy.json");

    //Read text from file
    StringBuilder text = new StringBuilder();

    try {
        BufferedReader br = new BufferedReader(new FileReader(fileEvents));
        String line;

        while ((line = br.readLine()) != null) {
            text.append(line);
            text.append('\n');
        }
        br.close();
    }
    catch (IOException e) {
        //You'll need to add proper error handling here
    }

//you now have the file content in the text variable and you can use it 
//based on you needs
Log.d("MYAPP",text.toString());

Upvotes: 1

Related Questions