Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


Java Programming Code Examples

Java > Core Java Code Examples

Serialize an Object to a File

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
Serialize an Object to a File import java.util.Vector; import java.io.*; public class Queue extends Vector { /* ** FIFO, first in first out */ Queue() { super(); } void put(Object o) { addElement(o); } Object get() { if (isEmpty()) return null; Object o = firstElement(); removeElement(o); return o; } Object peek() { if (isEmpty()) return null; return firstElement(); } } //To serialize (save the Queue state to a file) : public static void main(String args[]) { Queue theQueue; theQueue = new Queue(); theQueue.put("element 1"); theQueue.put("element 2"); theQueue.put("element 3"); theQueue.put("element 4"); System.out.println(theQueue.toString()); // serialize the Queue System.out.println("serializing theQueue"); try { FileOutputStream fout = new FileOutputStream("thequeue.dat"); ObjectOutputStream oos = new ObjectOutputStream(fout); oos.writeObject(theQueue); oos.close(); } catch (Exception e) { e.printStackTrace(); } } //To unserialize (to load a previously saved Queue) : public static void main(String args[]) { Queue theQueue; theQueue = new Queue(); // unserialize the Queue System.out.println("unserializing theQueue"); try { FileInputStream fin = new FileInputStream("thequeue.dat"); ObjectInputStream ois = new ObjectInputStream(fin); theQueue = (Queue) ois.readObject(); ois.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println(theQueue.toString()); }