繁体   English   中英

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

[英]Android - How can I read a text file from a url?

我上传了一个文本文件(* .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错误: httpt.setText(urls.get(0));它用t.setText(urls.get(0));突出显示该行t.setText(urls.get(0));

提前致谢 !!!

尝试使用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-)为您的清单文件添加Internet权限。

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();

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

public String txt;

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

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

像这样delare 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;

    }

现在使用所需的Url调用AsyncTask:

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

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

 <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" />

只需将其放入一个新线程并启动它将工作的线程。

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();

而已。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM