save SharedPreferences To File - Android Android OS

Android examples for Android OS:SharedPreferences

Description

save SharedPreferences To File

Demo Code

/*******************************************************************************
 * Copyright (c) 2014 Hoang Nguyen./*from  w  ww.j  ava  2s .co m*/
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Hoang Nguyen - initial API and implementation
 ******************************************************************************/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPOutputStream;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.preference.PreferenceManager;

public class Main {
  static String saveSharedPreferencesToFile(Context context) {
    try {
      File myFile = new File(GenerateFilename());
      myFile.createNewFile();
      return saveSharedPreferencesToFile(context, myFile);
    } catch (Exception e) {

      return null;
    }
  }

  static String saveSharedPreferencesToFile(Context context, File dst) {
    String res = null;
    ObjectOutputStream output = null;
    try {
      GZIPOutputStream outputGZIP = new GZIPOutputStream(new FileOutputStream(
          dst));
      output = new ObjectOutputStream(outputGZIP);
      SharedPreferences pref = PreferenceManager
          .getDefaultSharedPreferences(context);
      Map<String, Object> shallowCopy = new HashMap<String, Object>(
          pref.getAll());
      shallowCopy.remove("extendedlog");
      output.writeObject(shallowCopy); // write everything but not the log
      res = dst.getAbsolutePath();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (output != null) {
          output.flush();
          output.close();
        }
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
    return res;
  }

  static String GenerateFilename() {
    String logfile = Environment.getExternalStorageDirectory().getPath()
        + "/screenstandby" + getDateTime() + ".backup-ss";
    return logfile;
  }

  final static String getDateTime() {
    SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd-hhmmss");
    return df.format(Calendar.getInstance().getTime());
  }
}

Related Tutorials