How do I store data into a flat file in Android?
I want to store a few values in the f开发者_Go百科orm of high scores. But since I'm not going to be storing more than 5 values, using SQLite doesn't seem appropriate. Another option I was considering was a flat file, but I'm not sure how to go about that...
See here for your Data Storage options. I suppose that in your case the easiest will be to use SharedPreferences.
You could also use Internal Storage to save data in a file that is private to your application. I wouldn't recommend to use External Storage for storing high scores.
If it's an array you can use this:
public void saveArray(String filename, String[] output_field) {
try {
FileOutputStream fos = new FileOutputStream(filename);
GZIPOutputStream gzos = new GZIPOutputStream(fos);
ObjectOutputStream out = new ObjectOutputStream(gzos);
out.writeObject(output_field);
out.flush();
out.close();
}
catch (IOException e) {
e.getStackTrace();
}
}
@SuppressWarnings("unchecked")
public String[] loadArray(String filename) {
try {
FileInputStream fis = new FileInputStream(filename);
GZIPInputStream gzis = new GZIPInputStream(fis);
ObjectInputStream in = new ObjectInputStream(gzis);
String[] read_field = (String[])in.readObject();
in.close();
return read_field;
}
catch (Exception e) {
e.getStackTrace();
}
return null;
}
You just call it like this:
Save Array: saveArray("/sdcard/.mydata/data.dat", MyArray);
Load Array: String[] MyArray = loadArray("/sdcard/.mydata/data.dat");
You can see an example at http://androidworkz.com/2010/07/06/source-code-imageview-flipper-sd-card-scanner/
精彩评论