How do I serialize an object to a file?
2 Answers
Know the answer? Post it. Somebody with the same question will find it here.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
AartiRank #2,383 · 594 reputationPosted Nov 16, 2011, 8:55 PM EST
Satyapriya NayakRank #47 · 31.5K reputationPosted Nov 16, 2011, 9:23 PM EST
The object to be serialized must implement java.io.Serializable. This example serializes a javax.swing.JButton object.
Ex:-
Object object = new javax.swing.JButton("push me"); try { // Serialize to a file ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser")); out.writeObject(object); out.close(); // Serialize to a byte array ByteArrayOutputStream bos = new ByteArrayOutputStream() ; out = new ObjectOutputStream(bos) ; out.writeObject(object); out.close(); // Get the bytes of the serialized object byte[] buf = bos.toByteArray(); } catch (IOException e) { }