Android - 如何从网址读取文本文件?

kil*_*oge 3 java android

我上传了一个文本文件(*.txt)到服务器,现在我想读取文本文件...

没试好我试过这个例子.

ArrayList<String> urls=new ArrayList<String>(); //to read each line
TextView t; //to show the result
try {
        // Create a URL for the desired page
        URL url = new URL("mydomainname.de/test.txt"); //My text file location
        // Read all the text returned by the server
         BufferedReader in = new BufferedReader(new     InputStreamReader(url.openStream()));

    t=(TextView)findViewById(R.id.TextView1);
    String str;
    while ((str = in.readLine()) != null) {
        urls.add(str);


    }
    in.close();
   } catch (MalformedURLException e) {
  } catch (IOException e) {
 }
 t.setText(urls.get(0)); // My TextFile has 3 lines 
Run Code Online (Sandbox Code Playgroud)

应用程序正在关闭......它可以取决于域名吗?应该有IP吗?我发现while循环没有被执行.因为如果我将t.setText*放在while循环中则没有错误,并且TextView为空.LogCat错误:http://textuploader.com/5iijr它突出显示该行t.setText(urls.get(0));

提前致谢 !!!

Kus*_*han 10

尝试使用HTTPUrlConnection或OKHTTP请求获取信息,请尝试以下操作:

总是在后台线程中做任何类型的网络,否则android将抛出NetworkOnMainThread异常

new Thread(new Runnable(){

  public void run(){


    ArrayList<String> urls=new ArrayList<String>(); //to read each line
    //TextView t; //to show the result, please declare and find it inside onCreate()



    try {
         // Create a URL for the desired page
         URL url = new URL("http://somevaliddomain.com/somevalidfile"); //My text file location
         //First open the connection 
         HttpURLConnection conn=(HttpURLConnection) url.openConnection();
         conn.setConnectTimeout(60000); // timing out in a minute

         BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

         //t=(TextView)findViewById(R.id.TextView1); // ideally do this in onCreate()
        String str;
        while ((str = in.readLine()) != null) {
            urls.add(str);
        }
        in.close();
    } catch (Exception e) {
        Log.d("MyTag",e.toString());
    } 

    //since we are in background thread, to post results we have to go back to ui thread. do the following for that

    Activity.this.runOnUiThread(new Runnable(){
      public void run(){
          t.setText(urls.get(0)); // My TextFile has 3 lines
      }
    });

  }
}).start();
Run Code Online (Sandbox Code Playgroud)


Bur*_*kir 5

1-) 为您的清单文件添加互联网权限。

2-) 确保您在单独的线程中启动代码。

这是对我有用的片段。

    public List<String> getTextFromWeb(String urlString)
    {
        URLConnection feedUrl;
        List<String> placeAddress = new ArrayList<>();

        try
        {
            feedUrl = new URL(urlString).openConnection();
            InputStream is = feedUrl.getInputStream();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));          
            String line = null;

            while ((line = reader.readLine()) != null) // read line by line
            {
                placeAddress.add(line); // add line to list
            }
            is.close(); // close input stream

            return placeAddress; // return whatever you need
        } 
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return null;
    }
Run Code Online (Sandbox Code Playgroud)

我们的 reader 函数已经准备好了,让我们使用另一个线程来调用它

            new Thread(new Runnable()
            {
                public void run()
                {
                    final List<String> addressList = getTextFromWeb("http://www.google.com/sometext.txt"); // format your URL
                    runOnUiThread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            //update ui
                        }
                    });
                }
            }).start();
Run Code Online (Sandbox Code Playgroud)