【问题标题】:FileOutputStream error文件输出流错误
【发布时间】:2011-02-21 14:38:01
【问题描述】:

我有一部分代码假设从网站获取图像并将其存储到 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(文件路径 + "/" + this.filename);

到第 2 次 try/catch,那么它将在第 2 次 catch 中发生。 可以帮我解决这个问题吗?

【问题讨论】:

  • “错误” - 什么错误?怎么了?
  • 我在我的 sdcard 中找不到图像,我在 logcat 中没有看到任何错误消息
  • 我刚刚从 catch 中收到一条错误消息,指出“java.io.FileNotFoundException: /sdcard/”

标签: fileoutputstream


【解决方案1】:

也许尝试摆脱.getAbsolutePath()

这在 2.2 上适用于我:

FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + fileName);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多