1

我有一部分代码假设从网站获取图像并将其存储到 sdcard 中。当我在 sdk1.5 上开发时,可以找到以下代码。但是,在我将其更改为 android sdk 2.0 后,它现在无法正常工作。这条线有问题;FileOutputStream fos = new FileOutputStream(filepath + "/" + this.filename);

这是我拥有的代码:

  void downloadFile(String fileUrl) {
    URL myFileUrl = null;
    try {
        myFileUrl = new URL(fileUrl);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) myFileUrl
                .openConnection();
        conn.setDoInput(true);
        conn.connect();

        InputStream is = conn.getInputStream();

        bmImg = BitmapFactory.decodeStream(is);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        String filepath = Environment.getExternalStorageDirectory()
                .getAbsolutePath();
        FileOutputStream fos = new FileOutputStream(filepath + "/"
                + this.filename);
        bmImg.compress(CompressFormat.JPEG, 75, fos);
        fos.flush();
        fos.close();

        Context context = this.getBaseContext();
        new MediaScannerNotifier2(context, filepath + "/" + this.filename,
                "image/jpeg");

        // displaying download completion message
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Wallpaper Downloaded").setCancelable(false)
                .setPositiveButton("ok",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int id) {
                                dialog.cancel();
                                btn_setwall.setEnabled(true);
                                btn_download.setEnabled(false);
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    } catch (Exception e) {
        Log.e("MyLog", e.toString());
    }

}

错误发生在第三次捕获中。但是,当我移动这条线时

FileOutputStream fos = new FileOutputStream(filepath + "/" + this.filename);

到第二次尝试/捕获,然后它将发生在第二次捕获中。可以请帮助我吗?

4

1 回答 1

0

也许尝试摆脱.getAbsolutePath()

这在 2.2 上对我有用:

FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + fileName);
于 2010-10-07T18:11:12.700 回答