Skip to content

Instantly share code, notes, and snippets.

@9re
Created September 3, 2011 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 9re/1191332 to your computer and use it in GitHub Desktop.
Save 9re/1191332 to your computer and use it in GitHub Desktop.
copying shared_prefs
import android.content.Context;
import android.os.Environment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopySharedPrefs {
private static final String SHARED_PREFS = "shared_prefs";
public static void copySharedPrefs(Context context) {
File filesDir = context.getFilesDir();
filesDir = filesDir.getParentFile();
if (filesDir != null) {
filesDir = new File(filesDir, SHARED_PREFS);
File targetDir = Environment.getExternalStorageDirectory();
if (targetDir != null) {
targetDir = new File(targetDir, "." + context.getPackageName() + "/" + SHARED_PREFS);
if (!targetDir.exists()) {
targetDir.mkdirs();
}
for (File sharedPref : filesDir.listFiles()) {
try {
copy(sharedPref, targetDir);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
private static void copy(File sharedPref, File targetDir) throws FileNotFoundException {
FileInputStream inputStream = new FileInputStream(sharedPref);
File outFile = new File(targetDir, sharedPref.getName());
FileOutputStream outputStream = new FileOutputStream(outFile);
final int BUFFER_SIZE = 8192;
byte[] buffer = new byte[BUFFER_SIZE];
try {
for (;;) {
int read = inputStream.read(buffer, 0, BUFFER_SIZE);
if (read > -1) {
outputStream.write(buffer, 0, read);
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment