Search code examples
androidsharedpreferencesfileinputstream

How to export my sharedPreferences file


Hello i'n my application i want to backUp the SharedPrefernces file to my device storage . i tried to export it like i'm exporting my database file but it given me an error."java.io.filenotfoundexception /data/data/ com.example.myapp/shared_prefs/ myPref: open failed: ENOENT (no such file or diractory) here is my code:

@SuppressLint("SdCardPath")
private void exportPref() throws IOException {
      // Open your local db as the input stream
    try {
        String inFileName = "/data/data/com.bibas.workclocks/shared_pref/"+MySharedPreferences.MY_TEMP;
        File dbFile = new File(inFileName);
        FileInputStream fis = new FileInputStream(dbFile);

        String outFileName = Environment.getExternalStorageDirectory()+ "/MyPrefs";

        // Open the empty db as the output stream
        OutputStream output = new FileOutputStream(outFileName);
        // transfer bytes from the inputfile to the outputfile
        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();
    }
    Toast.makeText(context,
            "'",
            Toast.LENGTH_LONG).show();
}

Solution

  • See this post for a working example on saving SharedPreferences.