控制台程序。
首先定义一个含有任意不同数据类型域的可序列化类:
import java.io.Serializable; public class Junk implements Serializable {
private static java.util.Random generator = new java.util.Random();
private int answer; // The answer
private double[] numbers; // Valuable data
private String thought; // A unique thought
private static final long serialVersionUID = 9001L; public Junk(String thought) {
this.thought = thought;
answer = 42; // Answer always 42 numbers = new double[3 + generator.nextInt(4)]; // Array size 3 to 6
for(int i = 0 ; i < numbers.length ; ++i) { // Populate with
numbers[i] = generator.nextDouble(); // random values
}
} @Override
public String toString() {
StringBuffer strBuf = new StringBuffer(thought);
strBuf.append('\n').append(String.valueOf(answer));
for(int i = 0 ; i < numbers.length ; i++) {
strBuf.append("\nnumbers[")
.append(String.valueOf(i))
.append("] = ")
.append(numbers[i]);
}
return strBuf.toString();
}
}
然后使用如下程序能将这个类类型的对象写入到文件中:
import java.io.*;
import java.nio.file.*;
import java.io.IOException; public class SerializeObjects {
public static void main(String[] args) {
Junk obj1 = new Junk("A green twig is easily bent.");
Junk obj2 = new Junk("A little knowledge is a dangerous thing.");
Junk obj3 = new Junk("Flies light on lean horses."); Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("JunkObjects.bin");
try {
Files.createDirectories(file.getParent()); // Make sure we have the directory
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
} try (ObjectOutputStream objectOut = new ObjectOutputStream(new BufferedOutputStream(Files.newOutputStream(file)))){
// Write three objects to the file
objectOut.writeObject(obj1); // Write object
objectOut.writeObject(obj2); // Write object
objectOut.writeObject(obj3); // Write object
System.out.println("\n\nobj1:\n" + obj1
+"\n\nobj2:\n" + obj2
+"\n\nobj3:\n" + obj3); } catch(IOException e) {
e.printStackTrace();
}
}
}