在Android应用中从服务器读取文本文件

时间:2012-03-09 21:58:38

标签: java android file

  

可能重复:
  android.os.NetworkOnMainThreadException

我想从TextView中的服务器打开一个文本文件(一行几行),但是当我打开活动时,我当前的代码会崩溃应用程序。我试过了:

urlTextOut = (TextView) findViewById(R.id.URLtextView); 
StringBuilder text = new StringBuilder();

try {
    String str = "";
    URL url = new URL("http://mysite.com/text1.txt");

    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

    while ((str = in.readLine()) != null) {
         text.append(str);
    }
    in.close();
} catch (MalformedURLException e1) {
} catch (IOException e) {
}

urlTextOut.setText(text);

我也尝试过与此非常类似的东西:How to read text file in android from web?(添加了尝试/捕获它想要的地方),但这也使应用程序崩溃了。我已经尝试过查看Apache的HttpComponents,但无法弄清楚我对下载的zip文件的意图。

1 个答案:

答案 0 :(得分:0)

你可能得到NetworkOnMainThreadException。 Android不允许您在主/ UI线程上进行网络调用(即直接在您的Activity中)。您应该使用单独的帖子see this question for an example