Saving int/byte/string data types in Android
Sorry, this might be quite a lengthy question, but how do i actually save int/byte/string data types in Android?
I do know that to save a String into the internal memory (note, not external or anything else), i have to do something like this:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
to save the file, and:
int saveTest = fos.read();
fos.close();
to read the file from another activity or something. (Is this correct?)
But what if i want to save and read the file as an int/byte data file? Is this possible? And how would i be able to do it?
To save your objects you can use the ObjectOutput class to serialize them, eg:
// Example object which implements Serializable
Example example = new Example();
// Save an object
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(getCacheDir(),"")+"cacheFile.srl"));
out.writeObject( new Integer( YOUR_INT ) );
out.close();
// Load in an object
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(new File(getCacheDir(),"")+"cacheFile.srl")));
Integer example_loaded = (Integer) in.readObject();
in.close();
Where the class Example could be any object that implements serializable or byte data, the javadocs may also help!
Hope this helps!
If you want to read objects, then you would create an ObjectInputStream
from the FileInputStream
you got. If you want to read the file as binary, then you can use the read
member function that works with a byte[]
.
上一篇: 我如何编码单声道守护进程