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

时间:2016-07-14 11:07:17

标签: 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 

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

提前致谢!!!

4 个答案:

答案 0 :(得分:8)

尝试使用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();

答案 1 :(得分:3)

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;
    }

我们的读者功能已准备好,让我们使用另一个线程

来调用它
            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();

答案 2 :(得分:1)

声明一个字符串变量以保存文本:

public String txt;

声明一种检查连接性的方法:

private boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    return cm.getActiveNetworkInfo() != null;
}

删除这样的AsyncTask:

private class ReadFileTask extends AsyncTask<String,Integer,Void> {

    protected Void doInBackground(String...params){
        URL url;
        try {
            //create url object to point to the file location on internet
            url = new URL(params[0]);
            //make a request to server
            HttpURLConnection con=(HttpURLConnection)url.openConnection();
            //get InputStream instance
            InputStream is=con.getInputStream();
            //create BufferedReader object
            BufferedReader br=new BufferedReader(new InputStreamReader(is));
            String line;
            //read content of the file line by line
            while((line=br.readLine())!=null){
                txt+=line;

            }

            br.close();

        }catch (Exception e) {
            e.printStackTrace();
            //close dialog if error occurs
        }

        return null;

    }

现在使用所需的网址调用AsyncTask:

if(isNetworkConnected())
    {
        ReadFileTask tsk=new ReadFileTask ();
        tsk.execute("http://mystite.com/test.txt");
    }

并且不要忘记在清单中添加以下权限:

 <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

答案 3 :(得分:1)

只需将其放入新线程中并启动它将起作用的线程。

new Thread(new Runnable() 
    {
    @Override
    public void run()
    { 
    try
    {

    URL url = new URL("https://texts-8e2bd.firebaseapp.com/");//my app link change it

    HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
    BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
    String line;
    StringBuilder lin2 = new StringBuilder();
    while ((line = br.readLine()) != null) 
    {
    lin2.append(line);
    }
     Log.d("texts", "onClick: "+lin2);
    } catch (IOException e)
    {
    Log.d("texts", "onClick: "+e.getLocalizedMessage());
    e.printStackTrace();
    }
    }
    }).start();

就这样。