Serializing an object
From CodeCodex
Contents
Implementations[edit]
Erlang[edit]
It changes given data into the binary and it outputs it in the file.
-module(codex). -export([serialize/2]). serialize(Filename, Term) -> Binary = term_to_binary(Term), io:format("~p~n", [Binary]), {ok, IoDevice} = file:open(Filename, [write]), file:write(IoDevice, Binary), file:close(IoDevice).
For example:
1> codex:serialize("binary.dat",{1,[2],true,"abc"}). <<131,104,4,97,1,107,0,1,2,100,0,4,116,114,117,101,107,0,3,97,98,99>> ok
Java[edit]
The object to be serialized must implement java.io.Serializable. This example serializes a javax.swing.JButton object.
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) { // Never leave a catch empty, even temporarily. e.printStackTrace(); }
- Original Source: The Java Developers Almanac 1.4
OCaml[edit]
The built-in Marshal module provides serialisation. For example:
# Marshal.to_string [1;2;3;4] [];; - : string = "\132\149¦¾\000\000\000\t\000\000\000\004\000\000\000\012\000\000\000\012 A B C D@"
Ruby[edit]
p Marshal.dump([1, 3.141, {:one=>1, :two=>2}, true, false]) #=> "\x04\b[\ni\x06f\r3.141\x00\xE3T{\a:\bonei\x06:\btwoi\aTF"