当前位置: 代码迷 >> Android >> 尝试保存文件,但即使尝试创建目录也获得“文件的父目录不存在”
  详细解决方案

尝试保存文件,但即使尝试创建目录也获得“文件的父目录不存在”

热度:48   发布时间:2023-08-04 10:53:34.0

我正在尝试将图像保存到我的SD卡中,但是遇到以下错误:

java.io.IOException: Parent directory of file does not exist: /sdcard/skdyImages/a46e2e08-9154-4fe7-96e8-2af0a7a92867.jpg

我的清单中确实有权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

这是我的代码:

String newName = UUID.randomUUID().toString();
            Bitmap bmp = ImageLoader.getInstance().getBitmap(e.getUrl());
            File file = new File("/sdcard/skdyImages", newName + ".jpg");
            file.getParentFile().mkdirs();
            file.createNewFile();
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
            bmp.compress(CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();

有任何想法吗?

试试这样的东西...

// Automatically creates folder on sdcard called /Android/data/<package>/files
// if it doesn't exist
File ImageDir = new File(getExternalFilesDir(null).getAbsolutePath());

BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(ImageDir + "/" + newName + ".jpg"));
  相关解决方案