从url下载文件并在本地稍后阅读

时间:2016-01-25 21:09:22

标签: android

我想从url下载文件,以便稍后在本地读取此文件。我有这个代码来下载文件:

private void startDownload() {
    String url = "my url";
    new DownloadFileAsync().execute(url);
}
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Actualizando programa..");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
    }
}
class DownloadFileAsync extends AsyncTask<String, String, String> {

    @SuppressWarnings("deprecation")
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @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("/myfile.json");

            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;

    }
    protected void onProgressUpdate(String... progress) {
         Log.d("ANDRO_ASYNC",progress[0]);
         mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void onPostExecute(String unused) {
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    }
}

我不知道使用此代码保存文件的位置以及如何在本地稍后读取此文件。

1 个答案:

答案 0 :(得分:1)

要将文件保存到您的应用目录,请使用以下命令:

//save to cache
    try {
         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(activity.getFilesDir(), "/myfile.json")));
        oos.writeObject(list);
        oos.flush();
        oos.close();

    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }

检索内容:

   ObjectInputStream dis = new ObjectInputStream(new FileInputStream(new File(context.getFilesDir(), "/myfile.json")));
    ArrayList<String> = (ArrayList<String>) dis.readObject();
        dis.close();

我希望它有所帮助!