我有一个AsyncTask将文件下载到我的Android应用程序的内部存储中。我想稍后阅读这个文件,但我不知道怎么能这样做。这是我的AsyncTask代码:
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 :(得分: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());