是否可以导入和导出SharedPreferences文件?

时间:2014-09-02 05:52:19

标签: android sharedpreferences

你好我的应用程序我将sharedPreferences文件导出到我的设备storge现在,我想再次将文件导入应用程序我该怎么做?这是导出的代码以及我尝试导入的内容:

       private void saveShared()
           {

               SharedPreferences prefs = context.getSharedPreferences(MySharedPreferences.MY_TEMP, 1);

               File myPath = new File(Environment.getExternalStorageDirectory().toString());
               File myFile = new File(myPath, MySharedPreferences.MY_TEMP.toString());

               try
               {
                   FileWriter fw = new FileWriter(myFile);
                   PrintWriter pw = new PrintWriter(fw);

                   Map<String,?> prefsMap = prefs.getAll();

                   for(Map.Entry<String,?> entry : prefsMap.entrySet())
                   {
                       pw.println(entry.getKey() + ": " + entry.getValue().toString());            
                   }

                   pw.close();
                   fw.close();

                Toast.makeText(context,
                        "Shared preferences saved!'",
                        Toast.LENGTH_LONG).show();
               }
               catch (Exception e)
               {

               }
           }

@SuppressLint("SdCardPath")
    public void importSharedPreferences() {
        try {

            FileInputStream fis = new FileInputStream(Environment.getExternalStorageDirectory().toString()); 

            String outFileName = "/data/data/com.bibas.workclocks/databases/"+MySharedPreferences.MY_TEMP.toString();
            OutputStream output = new FileOutputStream(outFileName);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            // Close the streams
            output.flush();
            output.close();
            fis.close();




        } catch (Exception e) {
            Toast.makeText(context, e.toString(), Toast.LENGTH_LONG)
            .show();
        }
    }

0 个答案:

没有答案