开发者

Saving int/byte/string data types in Android

开发者 https://www.devze.com 2023-04-07 23:43 出处:网络
Sorry, this might be quite a lengthy question, but how do i actually save 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 possi开发者_开发百科ble? And how would i be able to do it?


To save your objects you can use the ObjectOutput class to serialize them, e.g.:

// 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[].

0

精彩评论

暂无评论...
验证码 换一张
取 消