android bug: FileNoFoundExecption

本文解决了在Android应用中创建Bitmap时遇到的FileNotFoundException问题。详细分析了错误原因,即在创建多级目录和文件时未正确区分处理,导致读写操作失败。提供了修改后的代码示例,展示了如何先创建目录再创建文件,确保应用程序正常运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题现象

原代码如下所示:

if (ze.getName().contains(".gif")) {
                    gifPath = Environment.getExternalStorageDirectory() + "/DCIM/NewCompete/" + ze.getName().replace("/", "_");
                    File gifFile = new File(gifPath);
                    if (!gifFile.exists()) {
                        copyFile(zf.getInputStream(ze), gifPath);
                    } else {
                        if (FileUtil.deleteFile(gifPath)) {//删除原来的安装文件再下载
                            copyFile(zf.getInputStream(ze), gifPath);
                        }
                    }
                }
       try {
            Bitmap map = BitmapFactory.decodeStream(new FileInputStream(picturePath));
            mapHeight = map.getHeight();
            map.recycle();

        } catch (Exception e) {
            Log.e("yushan", "" + e);
        }

每次创建Bitmap都会报FileNoFoundExecption。

bug原因

在创建多层File(包括要写入的文件)的时候,文件夹和文件要分开来创建,否则明明本地创建文件夹成功,但是在通过IO对指定的File进行读写时就会发生java.io.FileNotFoundException (Is a directory)

解决方法

                if (ze.getName().contains(".jpg")) {
                    picturePath = basePath + ze.getName().replace("/", "_");
                    PreferenceHelper.put(NewCompeteDetailActivity.this, PreferenceHelper.NEW_COMPETE, "picturePath:" + userid + activeId, picturePath);
                    File files = new File(basePath);
                    if (!files.exists()) {
                        files.mkdir();
                    }
                    File mapFile = new File(files + "/", ze.getName().replace("/", "_"));
                    if (!mapFile.exists()) {
                        copyFile(zf.getInputStream(ze), picturePath);
                    } else {
                        if (FileUtil.deleteFile(picturePath)) {//删除原来的安装文件再下载
                            copyFile(zf.getInputStream(ze), picturePath);
                        }
                    }
                }

希望可以解决你的问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值