0

I need to download a text file from a server and just save it in memory. Then go line by line and read it. Better off - read line by line directly from the server.

EDIT: 'save it in memory' means without writing it to a file.

How would you do that?

Thanks!

Roman
  • 4,443
  • 14
  • 56
  • 81

3 Answers3

8

What's so impossible about it ? Try this code: Notice that CONTEXT creating the file could be an Activity/ApplicationContext/etc.

public boolean downloadFile(final String path)
    {
        try
        {
            URL url = new URL(path);

            URLConnection ucon = url.openConnection();
            ucon.setReadTimeout(5000);
            ucon.setConnectTimeout(10000);

            InputStream is = ucon.getInputStream();
            BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);

            File file = new File(CONTEXT.getDir("filesdir", Context.MODE_PRIVATE) + "/yourfile.png");

            if (file.exists())
            {
                file.delete();
            }
            file.createNewFile();

            FileOutputStream outStream = new FileOutputStream(file);
            byte[] buff = new byte[5 * 1024];

            int len;
            while ((len = inStream.read(buff)) != -1)
            {
                outStream.write(buff, 0, len);
            }

            outStream.flush();
            outStream.close();
            inStream.close();

        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }

        return true;
    }

It's a simple file R/W with the usage of the activity context .

EDIT : As per your recently changed question, I am posting this here :

Try this piece of code :

try {
    // Create a URL for the desired page
    URL url = new URL("ksite.com/thefile.txt");

    // Read all the text returned by the server
    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) {
}

This should work

The Dark Knight
  • 5,455
  • 11
  • 54
  • 95
  • But you're writing it to a file. The idea is to read line by line directly from the server – Roman Jun 12 '13 at 13:10
  • No , the question that you posted initially says, you need to read it line by line after you save it. There you go. Once you have saved it, you can read it as you like , line by line or otherwise. What i have posted is just an android way of reading a file. How you want it to be read is up to you . – The Dark Knight Jun 12 '13 at 13:12
  • Sorry, I probably wasn't clear enough - I meant without saving to the sdcard / local memory. – Roman Jun 12 '13 at 13:15
  • That's ok, see my updated answer . – The Dark Knight Jun 12 '13 at 13:22
  • Unfortunately this won't strip out .mhtml file characters like: **From: X-Snapshot-Version: 1.0** – IgorGanapolsky Nov 03 '17 at 15:17
4

Try:

      String line;
      URL url = new URL("myserver.com/myfile.txt");    
      BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));    
      while ((line = in.readLine()) != null) {
          // do something with line
      }
      in.close();
CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
1

I did this. Just open a connection with your server (if it is a FTP server, just do it with FTPClient from the Apache commons). Get this connection setting up into a new AsyncTask<...,...,...> and place your connecting code into doInBackground(...). EDIT: I did it like this:

      FileOutputStream fos = activity.openFileOutput("temp.tmp", Context.MODE_PRIVATE);
      System.out.println(activity.getFilesDir().getAbsolutePath());
      client.enterLocalPassiveMode();
      client.changeToParentDirectory();
      client.changeWorkingDirectory("/dsct2c/" + username);
      client.retrieveFile(filename, fos);
      fos.close();
      publishProgress(activity.getString(R.string.toast_file_saved) + " " + filename);



      FileInputStream fis = activity.openFileInput("temp.tmp");
      InputStreamReader isr = new InputStreamReader(fis);
      BufferedReader br = new BufferedReader(isr);

      String line = br.readLine();
      while(line != null)
      {
        publishProgress(line);
        System.out.println(line);
        line = br.readLine();
      }
marc3l
  • 2,525
  • 7
  • 34
  • 62