Reputation: 501
I have been using this code:
public void saveCredits(int myInt) {
try {
OutputStream fos = openFileOutput("test.txt", Context.MODE_PRIVATE);
DataOutputStream dis = new DataOutputStream(fos);
dis.writeInt(myInt);
fos.flush();
fos.close();
}
catch (IOException e) {
System.out.println(e);
}
}
How do I modify it in the simplest way to also write an array of custom objects such as houses(String name, int cost, Address address)
Upvotes: 0
Views: 750
Reputation: 502
Easiest way with DataOutputStream is to:
Like this:
DataOutputStream out = ... ;
out.writeInt(items.length);
for (Item item : items) {
out.writeUTF(item.someString());
out.writeFloat(item.someFloat());
}
Loading such an array is easy too:
DataInputStream in = ... ;
int length = in.readInt();
Item[] items = new Item[length];
for (int i = 0; i < length; ++i) {
items.add(new Item(in.readUTF(), in.readFloat()));
}
Upvotes: 1