Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

save image to sdcard android Directory problem

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){

        }

ErrorLog:

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?

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

Edit - to create directories:

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

Then you can save a file to root + "/mvc/mvc/foo.png".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...