无法将位图写入SD卡

时间:2015-01-01 23:37:13

标签: android android-sdcard fileoutputstream

我正在尝试将位图写入SD卡(作为Png文件),查找以下代码

File file = new File(getExternalFilesDir(null), "DemoFile.png");
OutputStream os = new FileOutputStream(file);
Log.d("JS", "File name -> " + file.getAbsolutePath());
//File name -> /mnt/sdcard/Android/data/com.pocmodule/files/DemoFile.png
bmp.compress(Bitmap.CompressFormat.PNG, 90, os); //here bmp is of type 'Bitmap'
os.close();

但我没有看到文件' DemoFile.png'在SD卡中创建。更别说Png文件,我甚至没有看到目录' com.pocmodule'可在SD卡中使用。

我的代码中遗漏了什么吗?

2 个答案:

答案 0 :(得分:2)

  

我安装了我的设备(选择了USB调试模式)并浏览了目录

这不会探索文件系统。它探讨了MediaStore已知的内容。

首先,在flush()上调用getFD().sync(),然后调用FileOutputStream,然后再调用close(),以确保所有字节都写入磁盘。< / p>

然后,使用MediaScannerConnectionscanFile()MediaStore讲授您的档案。

这可能仍然需要你做某些&#34;刷新&#34;在桌面操作系统的文件浏览器窗口中,可以看到更改,甚至可能拔掉并重新插入设备,因为桌面操作系统可能会缓存&#34;目录&#34;内容。

答案 1 :(得分:1)

感谢@CommonsWare的帮助。我终于在SD卡上有了Png文件:)。对于想要了解工作代码的人,请在下面找到

File file = new File(getExternalFilesDir(null), "DemoFile.png");
FileOutputStream os = new FileOutputStream(file);
    Log.d("JS", "File name -> " + file.getAbsolutePath());
    //Here 'bmp' is of type Bitmap
    bmp.compress(Bitmap.CompressFormat.PNG, 90, os); 
    os.flush();
    os.getFD().sync();
    os.close();

    MediaScannerConnection.scanFile(this,
            new String[]{file.toString()}, null,
            new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    Log.i("ExternalStorage", "Scanned " + path + ":");
                    Log.i("ExternalStorage", "-> uri=" + uri);
                }
            });
相关问题