Question

I would rather my application save the required text file in the internal storage for the app than the users /sdcard/ so there isn't files being created which may annoy them at some point. Could someone direct me on how to change my code so the text file is saved internally rather than externally.

        public void updatebutton(View v){
        startDownload();
    }

    private void startDownload() {
        String url = "http://nowactivity.webs.com/teststring.txt";
        Toast.makeText(this, "Updating", Toast.LENGTH_LONG);
        new DownloadFile().execute(url);
    }


class DownloadFile extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... aurl) {
        int count;

    try {

    URL url = new URL(aurl[0]);
    URLConnection conexion = url.openConnection();
    conexion.connect();

    int lenghtOfFile = conexion.getContentLength();
    Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

    InputStream input = new BufferedInputStream(url.openStream());
    OutputStream output = new FileOutputStream("/sdcard/textfile.txt");

    byte data[] = new byte[1024];

    long total = 0;

        while ((count = input.read(data)) != -1) {
            total += count;
            publishProgress(""+(int)((total*100)/lenghtOfFile));
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();
    } catch (Exception e) {}
    return null;

    }
Was it helpful?

Solution

I think what you want is Context.openFileOutput(). (Activity extends Context, so you could call this from within an Activity, for instance.)

Incidentally, you should use Environment.getExternalStorageDirectory() instead of something like "/sdcard"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top