serialization.java

来自「国外的数据结构与算法分析用书」· Java 代码 · 共 31 行

JAVA
31
字号
import java.io.*;

/**	A small program that creates a small array, serializes it, and writes it to
	a file.  The array object is then discarded and the array  read back in from the file. */
public class Serialization
{
	public static void main(String[] args) throws Exception
	{
		int[] array = {3, 45, 53, 13, -5};
		for (int i = 0; i < array.length; i++)
			System.out.print(array[i] + " "); // display array contents
		System.out.println();
		FileOutputStream fos = new FileOutputStream("SerializedData");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(array); // write serialized array to file
		oos.flush();
		oos.close();

		array = null; // discard the array object
		System.out.println("array is now: " + array); // show that array is gone

		FileInputStream fis = new FileInputStream("SerializedData");
		ObjectInputStream ois = new ObjectInputStream(fis);
		array = (int[]) ois.readObject(); // read array back from file
		ois.close();
		for (int i = 0; i < array.length; i++)
			System.out.print(array[i] + " "); //display array contents
		System.out.println();
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?