我是android的新手。我需要从Web上读取文本文件并显示该文本文件。是否有可能直接在android中查看文本文件。或者如何在android textview中阅读和显示文本文件?
答案 0 :(得分:21)
使用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);
希望这有帮助!
答案 1 :(得分:6)
@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/");
帮助@Leandros
答案 2 :(得分:2)
此处发布的答案Android Read contents of a URL (content missing after in result)告诉您除了在文本视图中设置文本之外还要做什么