Saving and loading files from SD card

This is especially useful for saving (and loading) your game's state. It uses SD card by default, but it degrades gracefully to internal memory when the SD card is unavailable. "Why should I save game state to SD card?", you might ask. Well, large part of Android users are using custom ROMs on their devices. They upgrade it often and they often have to wipe the internal memory. Nobody wants to lose progress in any game, so storing it SD card seems better to me. Besides, if you switch phones, it's easy to copy or backup your savegames. Digression aside, let's dive into the code!

 1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829
public static boolean saveFile(String fileName, Context context) {
try {
File sdDir = Environment.getExternalStorageDirectory();
String path = sdDir.getAbsolutePath() + "/YOUR_DIR_NAME/";
File sgDir = new File(path);
if (!sgDir.exists()) {
sgDir.mkdirs();
sgDir.createNewFile();
}
FileWriter fw = new FileWriter(path + fileName);
BufferedWriter out = new BufferedWriter(fw);
String toSave = "I want to be saved in a file!";
out.write(toSave);
out.close();
return true;
}
catch (Exception ex) {
try {
FileOutputStream os = context.openFileOutput(fileName, 0);
String toSave = "I want to be saved in a file!";
os.write(toSave.getBytes());
os.flush();
os.close();
return true;
}
catch (Exception ex2) {}
}
return false;
}
This is a function for saving. What's going on here? There are two unobvious things:

  • getExternalStorageDirectory() - returns the root SD card directory (it's a method of android.os.Environment). Use this, instead of hardcoding the /sdcard (or any other) path!
  • context.openFileOutput(fileName, 0) - opens a file associated with this Context's application package (in device's internal memory). More info in the docs.
The rest is just standard Java I/O stuff. Function for loading:
 1 2 3 4 5 6 7 8 91011121314151617181920212223
public static String loadFile(String fileName, Context context) {
try {
File sdDir = Environment.getExternalStorageDirectory();
FileInputStream is = new FileInputStream(sdDir.getAbsolutePath() + "/YOUR_DIR_NAME/" + name);
byte[] byteArray = new byte[is.available()];
is.read(byteArray, 0, byteArray.length);
String content = new String(byteArray);
is.close();
return content;
}
catch (Exception ex) {
try {
FileInputStream is = context.openFileInput(fileName);
byte[] byteArray = new byte[is.available()];
is.read(byteArray, 0, byteArray.length);
String content = new String(byteArray);
is.close();
return content;
}
catch (Exception ex2) {}
}
return null;
}
Nothing new here. Checking whether the given file exists:
 1 2 3 4 5 6 7 8 910111213141516
public static boolean fileExists(String fileName, Context context) {
File sdDir = Environment.getExternalStorageDirectory();
File sg = new File(sdDir.getAbsolutePath() + "/YOUR_DIR_NAME/");
if (sg.exists())
return true;
else
try {
FileInputStream is = context.openFileInput(fileName);
if (is != null)
return true;
}
catch (Exception ex) {
return false;
}
return false;
}

2 Response to "Saving and loading files from SD card"

  1. Unknown says:

    It appears only an example. Can you gave me an actual sample on how to program or code it? Your example is not clearly understandable. Please?

    Thotep says:

    This is an actual, working code (at least it worked when I wrote this post, in 2010 ;))! What exactly isn't clear to you?

Prześlij komentarz

Powered by Blogger