【发布时间】:2019-10-14 10:37:39
【问题描述】:
android 中的共享首选项使用 XML 文件来读取/写入数据,那么如果我们使用 File 而不是 SharedPreferences,为什么它们不会抛出异常。
从文件中读取数据的示例代码。我们必须捕获异常。
private void readFile(Context context){
FileInputStream fis;
try {
fis= context.openFileInput("FileName"); // open file for reading
fis.read();
} catch (FileNotFoundException e){
} catch (IOException e){
}
}
从 SharedPreferences 读取数据的示例代码。无需捕获异常。
private void readSharedPreference(Context context) {
SharedPreferences settings = context.getSharedPreferences("FileName", Context.MODE_PRIVATE);
String testRead = settings.getString("sample", "");
// above statement does not throw IOException.(however it reads from file).
}
【问题讨论】:
-
您使用了哪种类型的文件而不是 SharedPreferences?
-
如果我们使用 FileOutputStream,如果该名称的文件不存在,它会抛出 FileNotFound 异常。然后,如果我们将数据写入文件,则会抛出 IOException
-
共享偏好与您的问题有何关联?请提供您遇到的错误代码
-
我没有收到任何错误,我只是好奇共享首选项如何管理异常(因为它们在后台使用文件)
标签: android xml file sharedpreferences