Reputation: 57
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?
Upvotes: 0
Views: 1210
Reputation: 37566
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();
Upvotes: 0
Reputation: 4265
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
Upvotes: 1
Reputation: 272237
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.
Upvotes: 1
Reputation: 1533
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.
Upvotes: 0