Is There A Way To Store SharedPreferences to SDcard?

前提是你 提交于 2019-12-12 13:41:25

问题


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 seems to be one way to go about it but I want to share this application and settings, and my phone is not rooted.

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.


回答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



来源:https://stackoverflow.com/questions/43312275/is-there-a-way-to-store-sharedpreferences-to-sdcard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!