简体   繁体   中英

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

I uploaded a text file(*.txt) to a server, now I want to read the text file...

I tried this example without luck.

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 

App is closing itself... Can it be up to the domain name ? Should there be a IP instead ? I figured out that the while loop isn't executed. Because if I put t.setText* in the while loop there is no error, and the TextView is empty. LogCat Error : http://textuploader.com/5iijr it highlight the line with t.setText(urls.get(0));

Thanks in Advance !!!

Try using an HTTPUrlConnection or a OKHTTP Request to get the info, here try this:

Always do any kind of networking in a background thread else android will throw a NetworkOnMainThread Exception

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-) Add internet permission to your Manifest file.

2-) Make sure that you are launching your code in separate thread.

Here is the snippet which works for me great.

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

Our reader function is ready, let's call it by using another thread

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

declare a string variable to save text:

public String txt;

declare a method to check connectivity:

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

delare an AsyncTask like this:

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;

    }

now call AsyncTask with desired Url:

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

and dont forget to add following permission in 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" />

just put it inside a new thread and start the thread it will work.

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

thats it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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