[英]Android studio, File.properties deleted after reopening the app
I saved a File.properties in this.getFilesDir() + "Data.propertie"
.我在 this.getFilesDir
this.getFilesDir() + "Data.propertie"
中保存了一个 File.properties。 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可以看到我在文件中保存了数据,可以加载,但是打开app的时候,数据已经被删除了
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.首先
Context.getFilesDir
返回一个File
object。 This File
represents the private data directory of your app.此
File
代表您的应用程序的私有数据目录。
Then you do getFilesDir() + "foo"
which will implicitly call toString()
on the File
instance.然后你做
getFilesDir() + "foo"
这将在File
实例上隐式调用toString()
。 File.toString()
is equivalent to File.getPath
which does not necessarily return a trailing slash. File.toString()
等效于File.getPath
,它不一定返回斜杠。
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.这意味着,如果
getFilesDir()
在/data/app
返回一个File
,您的属性文件将变为/data/appdata.properties
,它不在您的数据文件夹中并且无法写入。
Instead, to get a File
within a directory you can create a new File
instance with that directory.相反,要在目录中获取
File
,您可以使用该目录创建一个新的File
实例。 eg:例如:
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这可确保您的属性文件位于该目录中,并防止文件分隔符出现任何问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.