Android, folder deleted after some time

2019-09-06 19:52发布

问题:

My app is creating a folder and then an xml file on the sdcard. But after some time the folder is deleted and the file with it. The file is used to store a backup of the data from the app.

I dont need something new to make backup but a description of why it happens. The folder is created in the root of the sdcard with the name 'backup'.

This is how I create the folder and file:

File path = new File(Environment.getExternalStorageDirectory() + "/backup/tet/");
path.mkdirs();
File backupdir = new File(path, getDateTime() + ".xml");
fos = new FileOutputStream(backupdir);
fos.write(encodeDb(ctx).getBytes());
fos.close();

This is how I read the file:

boolean parsed = false;
File file = new File(Environment.getExternalStorageDirectory() + "/backup/tet/" + filename);
fis = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
fis.read(buffer, 0, (int) file.length());
parsed = decodeDb(ctx, new String(buffer));
fis.close();

I hope you can help me to discuss the problem.

回答1:

Maybe some other app also uses a folder named "backup" and then deletes it? I would name the folder differently, to make sure it's specific for your app.



回答2:

Making a new folder for your app isn't usually recommended, as it can result in other apps using the same folders (as Ilya suggested) as well as cluttering the SD card (and what user likes that?) Instead, it's best to use the command getExternalFilesDir(). Here's what Google's developer guides have to say:

If you're using API Level 8 or greater, use getExternalFilesDir() to open a File that represents the external storage directory where you should save your files. This method takes a type parameter that specifies the type of subdirectory you want, such as DIRECTORY_MUSIC and DIRECTORY_RINGTONES (pass null to receive the root of your application's file directory). This method will create the appropriate directory if necessary. By specifying the type of directory, you ensure that the Android's media scanner will properly categorize your files in the system (for example, ringtones are identified as ringtones and not music). If the user uninstalls your application, this directory and all its contents will be deleted.