user3410162
user3410162

Reputation: 11

Download a text file from the web - Android/ Java

I'm trying to get save a text file from the internet into a folder in my res directory (res/files) so I can then read and interpret it. My android manifest has set the appropiate permissions but when I test it in the simulator it fails.

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

Here's the method to get the file:

public void getTextFile(){
    String path ="http://hullmc.org.uk/cjvize/test.txt";
    URL u = null;
    try {
        u = new URL(path);
        BufferedReader in = new BufferedReader(new InputStreamReader(u.openStream()));
        int i = 0;
        String replicated = "";
        do{
            String str = in.readLine();
            replicated = replicated + "/n" + str;
            i++;
        }while(i<85);
        in.close();
    }
    catch(Exception e){
        welcome.setText("Failed");
    }
}

Can anyone suggest why this is not working? Many thanks!

Upvotes: 1

Views: 2723

Answers (2)

android developer
android developer

Reputation: 116352

you can't save into the resource folder of your app. you can't even store files into the assets folder.

there aren't even such folders when you install the app - they are all zipped into the APK . the res folder is a special one too, because each file there also creates a constant in the "R.java" file, so that it would be easier to reach and use. you can't reach such a thing when it's dynamic...

what you can do is to choose the right folder for you (read here), and download the file into there, using something like this :

InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(fullFilePath);
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1)
   output.write(data, 0, count);
//todo close streams and handle exceptions

if you use Apache commons library, you could minimize the code to just one line:

IOUtils.copy(new BufferedInputStream(url.openStream()), new FileOutputStream(fullFilePath));

Upvotes: 1

Cedric Simon
Cedric Simon

Reputation: 4659

This is working fine for me :

Use of class variable for View and Activity allow to keep code centralaized and shared, passing view as parameter, updated in constructor :)

1) Code to store the file locally

View newReport;
Activity reportActivity;    

private void downloadFile(String fileUrl, String fileName) {
    try{
        InputStream is = (InputStream) new URL(fileUrl).getContent();            
        FileOutputStream output = reportActivity.openFileOutput(fileName, newReport.getContext().MODE_PRIVATE);
        byte data[] = new byte[1024];
        int count;
        while ((count = is.read(data)) != -1)
            output.write(data, 0, count);
        output.flush();
        output.close();
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

It saves the file on the internal storage.

Then to save a file from URL, just call:

      downloadFile(myFileUrl, mySaveToFileName);

And to list your local files available:

        String[] fileList = newReport.getContext().fileList();
        for (String s : fileList){
            System.out.println("File found : "+s);
        }

Note: you do not require to save it locally to read it. If you prefer just to read it (to extract some info), let me know.

2) Code to "read and save to database", this should resolve:

// After InputStream declaration:
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null) 
 {
   //TODO Update database row concatenating inputLine to existing text value.
}
in.close();
in=null;
is.close();

Upvotes: 1

Related Questions