0

我宁愿我的应用程序将所需的文本文件保存在应用程序的内部存储中,而不是用户 /sdcard/,这样就不会创建可能在某些时候惹恼他们的文件。有人可以指导我如何更改我的代码,以便将文本文件保存在内部而不是外部。

        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;

    }
4

1 回答 1

0

我想你想要的是Context.openFileOutput()。(例如,Activity 扩展了 Context,因此您可以从 Activity 中调用它。)

顺便说一句,你应该使用Environment.getExternalStorageDirectory()而不是像"/sdcard"

于 2013-07-03T18:53:34.687 回答