Skip to content Skip to sidebar Skip to footer

Is There A Way To Store SharedPreferences To SDcard?

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. Share

Solution 1:

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.

References: here


Post a Comment for "Is There A Way To Store SharedPreferences To SDcard?"