我是 Android 的新手。我需要从网页中读取文本文件并显示该文本文件。是否有可能直接在 Android 中查看文本文件?否则,如何在 Android Textview 中读取并显示文本文件?
使用DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://www.urlOfThePageYouWantToRead.nl/text.txt");
HttpResponse response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line + "\n");
}
TextView.setText(total);
@BadSkillz 是对的,但在 API 的最后 9 个字符会出现错误:
android.os.NetworkOnMainThreadException
private class GetStringFromUrl extends AsyncTask<String, Void, String> {
ProgressDialog dialog ;
@Override
protected void onPreExecute() {
super.onPreExecute();
// show progress dialog when downloading
dialog = ProgressDialog.show(MainActivity.this, null, "Downloading...");
}
@Override
protected String doInBackground(String... params) {
// @BadSkillz codes with same changes
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(entity);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line + "\n");
}
String result = total.toString();
Log.i("Get URL", "Downloaded string: " + result);
return result;
} catch (Exception e) {
Log.e("Get Url", "Error in downloading: " + e.toString());
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// TODO change text view id for yourself
TextView textView = (TextView) findViewById(R.id.textView1);
// show result in textView
if (result == null) {
textView.setText("Error in downloading. Please try again.");
} else {
textView.setText(result);
}
// close progresses dialog
dialog.dismiss();
}
}
每次您需要使用时,请使用下面的行:
new GetStringFromUrl().execute("http://www.google.com/");
by helping @Leandros