1

I am learning Android and porting my Windows app to Android platform. I need an advice how to download a small text file and read content of this file.

I have following code in my Windows app, I need to rewrite it for Android app:

string contents = "file.txt";
string neturl = "http://www.example.com/file.txt";

HttpClient client = new HttpClient();

try {
   HttpResponseMessage message = await client.GetAsync(neturl);
   StorageFolder folderForFile = Windows.Storage.ApplicationData.Current.LocalFolder;
   StorageFile fileWithContent = await folderForFile.CreateFileAsync(channels, CreationCollisionOption.ReplaceExisting);
   byte[] bytesToWrite = await message.Content.ReadAsByteArrayAsync();
   await FileIO.WriteBytesAsync(fileWithContent, bytesToWrite);
   var file = await folderForFile.GetFileAsync(contents);
   var text = await FileIO.ReadLinesAsync(file);

   foreach (var textItem in text)
   {
   string[] words = textItem.Split(',');
   ...

I have found what on Android I need to create following class for async download

public class DownloadFileFromURL  extends AsyncTask<String, String, String> {

    /**
     * Downloading file in background thread
     * */
    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            // Output stream
            OutputStream output = new FileOutputStream("file.txt");

            byte data[] = new byte[1024];

            while ((count = input.read(data)) != -1) {

                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return null;
    }

In the code above I try to download file and name it as "file.txt", but get exception 'FileNotFoundException file.txt open failed: EROFS (Read-only file system)", I need to save it internally (I do not want to let users to see this file in the file explorers) and rewrite file if it exists. And I try to execute this task and read file

void DownloadAndReadContent() {
    new DownloadFileFromURL().execute("http://www.example.com/file.txt");

    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(openFileInput("file.txt")));
        String str = "";
        while ((str = br.readLine()) != null) {
            Log.d(LOG_TAG, str);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Anton
  • 907
  • 1
  • 10
  • 31
  • Download and save file on SD Card: http://stackoverflow.com/questions/25785609/android-downloading-a-file-and-saving-on-sd-card – xxx Nov 08 '15 at 15:03
  • 'new FileOutputStream("file.txt");'. You should use a full path. Or use openFileOutput(). – greenapps Nov 08 '15 at 15:06
  • how does full path look on android? – Anton Nov 08 '15 at 16:44
  • If I use "/data/data/packagename/files/file.txt" then "IllegalArgumentException File contains a path separator" – Anton Nov 08 '15 at 17:01

1 Answers1

3

so downloading to SD card is working

protected String doInBackground(String... f_url) {
        int count;
        try {
            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();
            InputStream input = new BufferedInputStream(url.openStream(), 8192);
            File SDCardRoot = Environment.getExternalStorageDirectory();
            SDCardRoot = new File(SDCardRoot.getAbsolutePath() + "/plus");
            SDCardRoot.mkdir();
            File file = new File(SDCardRoot,"settings.dat");
            FileOutputStream output = new FileOutputStream(file);
            byte data[] = new byte[1024];

            while ((count = input.read(data)) != -1) {
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }
        return null;
    }

and reading:

    new DownloadFileFromURL().execute("http://www.example.com/file.txt");
                if (!Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    Log.d(LOG_TAG, "SD n\a " + Environment.getExternalStorageState());
                    return;
                }
                File sdPath = Environment.getExternalStorageDirectory();
                sdPath = new File(sdPath.getAbsolutePath() + "/plus");
                File sdFile = new File(sdPath, "settings.dat");
                try {
                    BufferedReader br = new BufferedReader(new FileReader(sdFile));
                    String str = "";
                    while ((str = br.readLine()) != null) {
                        String[] words = str.split(",");
// do some work
                            }
                        }
                        Log.d(LOG_TAG, str);
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
Anton
  • 907
  • 1
  • 10
  • 31