I saved a File.properties in this.getFilesDir() + "Data.propertie".
In the app, I save the data that the user wrote, but when i open the app, all the data (or the file) that I saves from the previous time has been deleted.
Example:
// Store
for (Map.Entry<String,String> entry : MainActivity.Notes.entrySet()) { // Put all data from Notes in properties to store later
properties.put(entry.getKey(), entry.getValue());
}
try { properties.store(new FileOutputStream(this.getFilesDir() + "data.properties"), null); } // Store the data
catch (IOException e) { e.printStackTrace(); } // Error exception
// Load the map
Properties properties = new Properties(); // Crate properties object to store the data
try {
properties.load(new FileInputStream(this.getFilesDir() + "data.proprties")); } // Try to load the map from the file
catch (IOException e) { e.printStackTrace(); } // Error exception
for (String key : properties.stringPropertyNames()) {
Notes.put(key, properties.get(key).toString()); // Put all data from properties in the Notes map
}
// Can load the data
You can see that i saved the data in the file, and I can load it, but when I open the app, the data has been deleted
There is a way to write in the file and save the data that i write to the next time I open the app?
First off Context.getFilesDir returns a File object. This File represents the private data directory of your app.
Then you do getFilesDir() + "foo" which will implicitly call toString() on the File instance. File.toString() is equivalent to File.getPath which does not necessarily return a trailing slash.
This means, if getFilesDir() returns a File at /data/app, your properties file will become /data/appdata.properties which is not in your data Folder and cannot be written to.
Instead, to get a File within a directory you can create a new File instance with that directory. e.g:
File propertiesFile = new File(this.getFilesDir(), "data.properties");
// use propertiesFile for FileOutputStream/FileInputStream etc.
This ensures that your properties file is within that directory and prevents any issues from file separators