2

我想读取远程文本文件并在文本视图中显示其内容。我在下面的代码中编写了这个,但它没有从文本文件中获取任何信息。我怎样才能找到这个问题的原因或解决它?我的代码没有什么问题吗?

    private void readFile()
    {
         try {
            String path ="http://host.com/info.txt";
            URL u = new URL(path);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();
            InputStream in = c.getInputStream();
            Log.e("value",in.toString());
            AssetManager mngr=getAssets();
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            in.read(buffer); // Read from Buffer.
            bo.write(buffer); // Write Into Buffer.
            TextView text = (TextView) findViewById(R.id.TextView1);
            text.setText(bo.toString());
            bo.close();
            }
         catch (NetworkOnMainThreadException e) {
        }
            catch (MalformedURLException e) {
            e.printStackTrace();
            } catch (FileNotFoundException e) {
            e.printStackTrace();
            } catch (IOException e) {
            e.printStackTrace();
            }
    }
}
4

1 回答 1

4
  1. 您是否在清单文件中添加了 Internet 权限?
  2. 您是否在单独的线程中启动代码(请不要捕获 NetworkOnMainThreadException)
  3. 检查 LogCat 你有什么异常?
  4. 删除c.setDoOutput(true);了这个用于向服务器发送数据。

这里应该是这样的:

new Thread() {
            @Override
            public void run() {
                String path ="http://host.com/info.txt";
                URL u = null;
                try {
                    u = new URL(path);
                    HttpURLConnection c = (HttpURLConnection) u.openConnection();
                    c.setRequestMethod("GET");
                    c.connect();
                    InputStream in = c.getInputStream();
                    final ByteArrayOutputStream bo = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    in.read(buffer); // Read from Buffer.
                    bo.write(buffer); // Write Into Buffer.

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            TextView text = (TextView) findViewById(R.id.TextView1);
                            text.setText(bo.toString());
                            try {
                                bo.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }.start();
于 2013-06-17T06:55:37.193 回答