简体   繁体   中英

Android - cant save file to storage

I try to save file downloaded from internet with the following code

public static String saveToSdCard(Bitmap bitmap, String filename) {

    String stored = null;

    File sdcard = Environment.getExternalStorageDirectory() ;

    File folder = new File(sdcard.getAbsoluteFile(), ".tanks");
    boolean success = true; //the dot makes this directory hidden to the user

    if (!folder.exists()) {
        success = folder.mkdir();
    }

    if (success) {
        File file = new File(folder.getAbsoluteFile(), filename + ".jpg") ;
        if (file.exists())
            return stored ;

        try {
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
            stored = "success";
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    return stored;
}

but in runtime i get error like

03-04 20:42:51.080 8972-8972/com.example.me.demo2 E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/.tanks/4a100abb-0e55-4062-8c37-f11f4189e618.jpg: open failed: ENOENT (No such file or directory)

In my app manifest file I added permission

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

But when I launch app there is no alert asking for granting the permission.

Im I doing something wrong ?

Try to delete the folder and create it manually. Based on your code,

File tempFolder = new File(sdcard.getAbsoluteFile(), ".tanks");
tempFolder.mkdirs();
if (success) {
    File file = new File(tempFolder, filename + ".jpg") ;
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM