1

我正在开发一个应用程序,我想在其中将一些位图保存到 SD 卡中。我查看了很多示例和其他问题,并从中编写了以下代码:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
String dirPath = Environment.getExternalStorageDirectory().toString() + "/myFolder";
File dir = new File(dirPath);
dir.mkdirs();
String fileName = "bitmapname.jpg";
File file = new File(dirPath, fileName);
FileOutputStream fileOutPutStream;
try {
    boolean created = file.createNewFile();
    Log.d("Checks", "File created: " + created);
    fileOutPutStream = new FileOutputStream(file);
    fileOutPutStream.write(byteArrayOutputStream.toByteArray());
    fileOutPutStream.close();
} catch (FileNotFoundException e) {
    Log.d("Checks", "FileNotFoundException");
    e.printStackTrace();
} catch (IOException e) {
    Log.d("Checks", "IOException");
    Log.d("Checks", e.getMessage());
    e.printStackTrace();
}

我看不出这段代码有什么问题。它不会给出任何错误,并且我的应用程序运行时不会崩溃。但是,当我将手机连接到计算机并打开 SD 卡时,我看不到“myFolder”文件夹,也无法在任何地方找到保存的图像。你们有什么想法,为什么会这样?

编辑:我注意到我可以在 Android 库中看到保存的位图,它们确实位于名为“myFolder”的文件夹中。但是,当我将手机连接到计算机并浏览我的 SD 卡时,我仍然看不到它们。

4

2 回答 2

1

根据我的经验,当我忘记fileOutPutStream.flush();之前的close().

于 2013-05-18T20:36:49.557 回答
1

您确定要设置写入 SD 卡的权限吗?尝试设置这个:

   WRITE_EXTERNAL_STORAGE

编辑:好的,试试这个:

    Environment.getExternalStorageDirectory().getAbsolutePath()

代替:

    Environment.getExternalStorageDirectory().toString()

或者甚至创建一个这样的目录:

    File dir = new File(Environment.getExternalStorageDirectory() + 
                        File.separator + 
                        "myFolder");
    dir.mkdirs();
于 2013-05-18T21:14:46.177 回答