0

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)

1

2 Answers 2

1

Easiest way with DataOutputStream is to:

  1. store array size
  2. then items themselves

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()));
}
Sign up to request clarification or add additional context in comments.

Comments

0

Use ObjectOutPutStream and method writeObject().. Preciseley you need to Serialize and Deserialize your Objects.. more here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.