简体   繁体   中英

Read-only file system

I'm trying to store a png file in the internal memory of the phone, but I am having some difficulties.

I'm using this code:

private void storeImage(Bitmap image, String nombre) {
    try {
        File file = new File(name + ".png");
        file.createNewFile();
        FileOutputStream fos = new FileOutputStream(file);
        image.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.close();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, "Error accessing file: " + e.getMessage());
    }  
}

But it fails with this LogCat message:

Error accessing file: open failed: EROFS (Read-only file system)

I don't know how to change the permissions of the file or if there are better ways to store a png file in the phone.

Thanks!

Edit: since kitkat the use of Environment.getExternalStorageDirectory(); is discouraged, in favor of Context.getExternalFilesDir which returns the absolute path to the directory on the primary shared/external storage device where the application can place persistent files it owns. These files are internal to the applications, and not typically visible to the user as media. This directory and its content will be deleted upon uninstall of the app and you won't the WRITE_EXTERNAL_STORAGE use permission to use the returned directory.

The code you have is trying to write inside / which is read only. If you want to store your bitmap inside the SD card, you have to change:

File file = new File(nombre+".png");

into:

File root = Environment.getExternalStorageDirectory();
File file = new File(root, nombre+".png");

These two lines will attempt to write nombre+".png" into the root of your sdcard, polluting somehow the latter. The file will remain there untill you delete it manually and will be accessible to the all the apps installed on your phone. Mounting the sdcard on your pc or using a file browser will give you access to it as well.

These lines:

final FileOutputStream fos = openFileOutput(nombre+".png", Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();

write the file in the app private space in internal storage ( /data/data/you.app.name ). Since its private only your app will be able to access it. The only exception is if you have a rooted phone.

to retrieve it, you have to use:

final FileInputStream fis = openFileOutput(nombre+".png", Context.MODE_PRIVATE);

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