0

I have array of Shape:

Shape[] myshape = new Shape[13];

How I can save it to file?

I have found some code:

String fileName = "file.test";

BufferedOutputStream bs = null;

try {
    FileOutputStream fs = new FileOutputStream(new File(fileName));
    bs = new BufferedOutputStream(fs);
    bs.write(byte_array);
    bs.close();
    bs = null;
} catch (Exception e) {
    e.printStackTrace()
}

if (bs != null) try { bs.close(); } catch (Exception e) {}

But code work only for byte array, can anyone help me?

Abbas
  • 6,720
  • 4
  • 35
  • 49
JaLe29
  • 57
  • 1
  • 9
  • You need to make your Shape class Serializable. See: http://stackoverflow.com/questions/447898/what-is-object-serialization/447920#447920 – Rn222 Apr 24 '13 at 13:22

4 Answers4

1

Or you can use serialization to save the whole object.

Look at the javadoc:

http://docs.oracle.com/javase/6/docs/api/java/io/Serializable.html

And here a example from stackoverflow:

serialization/deserialization mechanism

Community
  • 1
  • 1
Kingalione
  • 4,237
  • 6
  • 49
  • 84
1

There are lots of options for saving objects, of which native Java serialisation is one. If you don't want to use serialisation, you could look at XStream, which will write POJOs out as XML.

The advantages are that it'll write out human-readable XML, and oyu don't have to implement particular interfaces for your objects. The disadvantage is that XML is relatively verbose.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
0

Try it like this:

Shape[] myshape = new Shape[13];

// populate array

// writing array to disk
FileOutputStream f_out = new FileOutputStream("C:\myarray.data");
ObjectOutputStream obj_out = new ObjectOutputStream (f_out);
obj_out.writeObject(array);

// reading array from disk
FileInputStream f_in = new FileInputStream("C:\myarray.data");
ObjectInputStream obj_in = new ObjectInputStream (f_in);
Shape[] tmp_array = (Shape[])obj_in.readObject();
CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
0

You have to serialize your shapes to turn them into a byte array. I don't think Shape implements serializable, so you'll to do that yourself.

DeadlyJesus
  • 1,503
  • 2
  • 12
  • 26