2014-02-13 66 views
1

我成功地在SharedPreferences中保存了偏好設置。我如何將預置文件保存在SD卡中,反之亦然? {我想給的選項給用戶的備份,這樣他就可以保存和載入的喜好跨重新intallations}保存sharedPreference文件

+0

你可以嘗試從複製和** /數據/數據/ your.app.name/shared_prefs/your.app.name。 preferences.xml ** –

+0

我想通過代碼來實現,稍後爲用戶實現選項 –

+0

當然,是通過代碼實現的。我不是故意手動的。 –

回答

1

要存儲在SD卡中sharedpreference你可以嘗試

private void backup(Context context) { 
    File root = context.getFilesDir(); 
    File parent = root.getParentFile(); 
    File[] files = parent.listFiles(); 
    File[] tmp = null; 
    for (File file : files) { 
     if (file.isDirectory()) { 
      tmp = file.listFiles(new FileFilter() { 
       @Override 
       public boolean accept(File pathname) { 
        return pathname.getName().contains("your_shared_preference_file_name"); 
       } 
      }); 
      if (tmp != null && tmp.length == 1) { 
       break; 
      } 
     } 
    } 

    File file = null; 
    if (tmp.length == 1) { 
     parent = tmp[0].getParentFile(); 
     file = new File(Environment.getExternalStorageDirectory(), "tmp.xml"); 
     FileInputStream fis = new FileInputStream(tmp[0]); 
     FileOutputStream fos = new FileOutputStream(file); 
     byte[] buffer = new byte[32768]; 
     int count = 0; 
     while ((count = fis.read(buffer)) > 0) { 
      fos.write(buffer, 0, count); 
     } 
     fis.close(); 
     fos.flush(); 
     fos.close(); 
    } 

}

0

終於有時間來完成項目

由於我用一個首選項文件來保存用戶數據,這是我用來複制它的代碼。

File fileSrc = new File(filePath, "userdata.xml"); 
File fileDes = new File("/data/data/com.nik/shared_prefs/", "userdata.xml"); 
... 
... 
private void copyFileToShared(File fileSrc, File fileDes) { 
FileInputStream fileinputstream=null; 
FileOutputStream fileoutputstream=null; 
try { 
fileinputstream = new FileInputStream(fileSrc); 
fileoutputstream = new FileOutputStream(fileDes); 
byte[] buffer = new byte[4096]; 
int count = 0; 
while ((count = fileinputstream.read(buffer)) > 0) { 
    fileoutputstream.write(buffer, 0, count); 
} 
fileinputstream.close(); 
fileoutputstream.flush(); 
fileoutputstream.close(); 
} 
catch(IOException e) { 
    e.printStackTrace(); 
} 
} 

和文件被複制... :-)