2016-01-26 2 views
0

У меня есть AsyncTask для загрузки файла на внутреннее хранилище в приложении для Android. Я хочу прочитать этот файл позже, но я не знаю, как это сделать. Это мой AsyncTask's код:Чтение файла из внутреннего хранилища

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

     } 


    } 

Я надеюсь, что это хороший код, если кто-то знает лучше практика, пожалуйста, скажите мне, как я могу это сделать.

ответ

0
//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()); 
+0

Привет! Код моего вопроса не работает, вы знаете, почему? спасибо –

+0

Если вы объясните мне, что значит «не работает», возможно, я могу вам помочь – Apperside

Смежные вопросы