1

I am using MonoDevelop for Android and would like some help to download a text file off the internet and to store it in a string.

Here is my code:

        try 
        {
            URL url = new URL("mysite.com/thefile.txt");

            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String str;
            while ((str = in.readLine()) != null) 
            {
                // str is one line of text; readLine() strips the newline character(s)
            }

            in.close();
        } 
        catch (MalformedURLException e) 
        {

        } catch (IOException e) 
        {

        }

I am getting the following error:

Invalid expression term 'in';

May I please have some help to get this code working. If there is an easier way to download a text file off the WWW and save the contents into a string, may I please have some help to implement it.

Thanks in advance.

Garry
  • 1,251
  • 9
  • 25
  • 45

1 Answers1

1

Here is the code we user for our project to download a website.

Just pass this function your URI and you will return a BufferedReader that contains the whole website.

   public static BufferedReader openConnection(URI uri) throws URISyntaxException, ClientProtocolException, IOException {
        HttpGet http = new HttpGet(uri);
        HttpClient client = new DefaultHttpClient();
        HttpResponse resp = (HttpResponse) client.execute(http);
        HttpEntity entity = resp.getEntity();
        InputStreamReader isr = new InputStreamReader(entity.getContent());
        BufferedReader br = new BufferedReader(isr, DNLD_BUFF_SIZE);
        return br;
    }

You can make uri the following way:

try{
    try{
    URI uri = new URI("mysite.com/thefile.txt");
    catch (Exception e){} //Should never occur

    BufferedReader in = openConnection(uri);
    String str;
        while ((str = in.readLine()) != null) 
        {
         // str is one line of text; readLine() strips the newline character(s)
        }
    in.close();
    } 
 catch (Exception e){
 e.printStackTrace();
 }

That should help you download the website.

Whitecat
  • 3,882
  • 7
  • 48
  • 78