2016-01-26 168 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

相關問題