有没有一种方法可以将SharedPreferences存储到SDcard? [英] Is There A Way To Store SharedPreferences to SDcard?
问题描述
我编写了一个具有几个硬编码设置的应用程序,例如fontSize或targetDirectory.我希望能够不经常更改这些类型的设置.
I've written an app that has several hard-coded settings such as fontSize or targetDirectory. I would like to be able to change those type of settings on an infrequent basis.
SharedPreferences似乎是解决此问题的一种方法,但我想共享此应用程序和设置,而且我的手机没有植根.
SharedPreferences seems to be one way to go about it but I want to share this application and settings, and my phone is not rooted.
我的应用程序是个人工具,没有UI.它打开,完成工作,然后关闭.我可以创建一个等效于Windows .ini文件的文件并对其进行读/写操作,但这似乎很笨拙.将SharePreferences文件放在我可以访问的sdcard上,而不是我无法访问的设备内存上,似乎可以正常工作.
My application is a personal tool, and does not have a UI. It opens, does it's job, and then closes. I could create the equivalent of a Windows .ini file and read/write to it, but that seems clunky. Having the SharePreferences file located on the sdcard where I can reach it, instead of device memory, where I can't, seems like that would work.
我不想备份这些首选项,只是希望能够对其进行编辑,或者将其复制到新设备上.
I do not want to backup these preferences, just be able to edit them, or copy them to a new device.
推荐答案
默认情况下,SharedPreferences文件存储在内部存储器中.您可以通过编程将其备份到SD卡.
By default SharedPreferences files are stored in internal storage. You can make a backup of it to SD card programmatically.
File ff = new File("/data/data/"
+ MainActivity.this.getPackageName()
+ "/shared_prefs/pref file name.xml");
copyFile(ff.getPath().toString(), "your sdcard path/save file name.xml");
private void copyFile(String filepath, String storefilepath) {
try {
File f1 = new File(filepath);
File f2 = new File(storefilepath);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
您可以在初次启动时将其替换回来,并在应用程序关闭时将其备份.
You may replace it back when first start and backup it when application closed.
参考文献:此处
这篇关于有没有一种方法可以将SharedPreferences存储到SDcard?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!