多くの場所で、すべてのメーカーが別の場所に配置しているため、SharedPreferences ファイルを SD カードにコピーするのが問題であることがわかりました。
ファイルの場所に関係なく、SDカードにバックアップしたい。これを行う方法はありますか?
多くの場所で、すべてのメーカーが別の場所に配置しているため、SharedPreferences ファイルを SD カードにコピーするのが問題であることがわかりました。
ファイルの場所に関係なく、SDカードにバックアップしたい。これを行う方法はありますか?
SharedPreferences
インターフェイスには、キーと値のペアを含むマップを返すメソッドが含まれていgetAll()
ます。そのため、ファイル自体をコピーする代わりに、このメソッドから返されたマップをシリアル化し、後で取得します。
いくつかのコード:
private boolean saveSharedPreferencesToFile(File dst) {
boolean res = false;
ObjectOutputStream output = null;
try {
output = new ObjectOutputStream(new FileOutputStream(dst));
SharedPreferences pref =
getSharedPreferences(prefName, MODE_PRIVATE);
output.writeObject(pref.getAll());
res = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (output != null) {
output.flush();
output.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return res;
}
@SuppressWarnings({ "unchecked" })
private boolean loadSharedPreferencesFromFile(File src) {
boolean res = false;
ObjectInputStream input = null;
try {
input = new ObjectInputStream(new FileInputStream(src));
Editor prefEdit = getSharedPreferences(prefName, MODE_PRIVATE).edit();
prefEdit.clear();
Map<String, ?> entries = (Map<String, ?>) input.readObject();
for (Entry<String, ?> entry : entries.entrySet()) {
Object v = entry.getValue();
String key = entry.getKey();
if (v instanceof Boolean)
prefEdit.putBoolean(key, ((Boolean) v).booleanValue());
else if (v instanceof Float)
prefEdit.putFloat(key, ((Float) v).floatValue());
else if (v instanceof Integer)
prefEdit.putInt(key, ((Integer) v).intValue());
else if (v instanceof Long)
prefEdit.putLong(key, ((Long) v).longValue());
else if (v instanceof String)
prefEdit.putString(key, ((String) v));
}
prefEdit.commit();
res = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return res;
}
誰かの役に立てば幸いです。何か問題があれば教えてください。
エラド
File ff = new File("/data/data/"
+ MainActivity.this.getPackageName()
+ "/shared_prefs/pref file name.xml");
Log.i("ddddddddddddd", ff.getPath() + "");
copyFile(ff.getPath().toString(), 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());
}
}