保存图片到SD卡的Andr​​oid目录问题目录、问题、图片、Andr

2023-09-13 23:54:15 作者:绝种好男人

我试着将数据保存到SD卡第一次我尝试使用getExternalFilesDir私下内的应用程序目录saave它externalStorage,但给了我NullPointerException异常,所以我尝试其他方式给出低于它的工作,但是当我想要的文件存储到一个自定义目录我想自己命名它给我的错误:

Im trying to save data to sdCard first i tried to saave it privately within app directory on externalStorage using getExternalFilesDir but gives me nullPointerException so i tried the other way given below it worked but when i want to store files into a custom directory that i want to named myself it give me error:

FileOutputStream os;
dirName = "/mydirectory/";
        try {  
            if (android.os.Environment.getExternalStorageState().equals(
                    android.os.Environment.MEDIA_MOUNTED)){
                File sdCard = Environment.getExternalStorageDirectory();
                File dir = new File (sdCard.getAbsolutePath() + dirName);
                dir.mkdirs();
                //File file = new File(this.getExternalFilesDir(null), this.dirName+fileName); //this function give null pointer exception so im using other one
                File file = new File(dir, dirName+fileName);
                os = new FileOutputStream(file);
            }else{
                os = context.openFileOutput(fileName, MODE_PRIVATE);
            }
            resizedBitmap.compress(CompressFormat.PNG, 100, os);
            os.flush();
            os.close();
        }catch(Exception e){

        }

错误日志:

java.io.FileNotFoundException:/mnt/sdcard/mvc/mvc/myfile2.png(没有这样的文件或目录)

java.io.FileNotFoundException: /mnt/sdcard/mvc/mvc/myfile2.png (No such file or directory)

推荐答案

您目录到/ mnt / SD卡/ MVC / MVC可能不存在。那么改变你的路径存储在 Environment.getExternalStorageDirectory()路径中的图像,然后从那里工作?

Your directory "/mnt/sdcard/mvc/mvc" may not exist. What about changing your path to store the image in the Environment.getExternalStorageDirectory() path and then working from there?

此外,罗伯特指出,要确保你有write允许在清单中的外部存储。

Also, as Robert pointed out, make sure you have write permission to external storage in your manifest.

修改 - 创建目录:

String root = Environment.getExternalStorageDirectory().toString();
new File(root + "/mvc/mvc").mkdirs();

然后就可以将文件保存到根+/mvc/mvc/foo.png