Java对象序列化实用方法集

有人问及相关问题,就顺便贴出代码。其实方法都很简单:
	//对象序列化写入文件
	public static void writeObject(Object obj, File file) throws FileNotFoundException, IOException {
		if (obj == null)
			throw new NullPointerException("obj are null.");
		ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(
				new FileOutputStream(file)));
		try {
			oos.writeObject(obj);
		} finally {
			oos.close();
		}
	}
  //对象序列化并压缩写入文件
	public static void writeCompressedObject(Object obj, File file) throws FileNotFoundException,
			IOException {
		if (obj == null)
			throw new NullPointerException("obj are null.");
		ObjectOutputStream oos = new ObjectOutputStream(new GZIPOutputStream(new FileOutputStream(
				file)));
		try {
			oos.writeObject(obj);
		} finally {
			oos.close();
		}
	}
	//从文件读取序列化的对象
	public static <T> T readObject(File src) throws IOException, ClassNotFoundException {
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(src)));
			return (T) ois.readObject();
		} finally {
			ois.close();
		}
	}
  //从文件读取序列化并压缩的对象
	public static <T> T readCompressedObject(File src) throws IOException, ClassNotFoundException {
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new GZIPInputStream(new FileInputStream(src)));
			return (T) ois.readObject();
		} finally {
			ois.close();
		}
	}


如果要对序列化结果做加密,原理类似,加密算法有很多,不多说了。
以上是Java对象序列化的文件操作,下面展示与字节数组的相互转换。
	public static <T extends Serializable> byte[] getBytes(T obj) throws IOException {
		byte[] b = serialize(obj, false).toByteArray();
		return b;
	}

	public static <T extends Serializable> byte[] getCompressedBytes(T obj) throws IOException {
		byte[] b = serialize(obj, true).toByteArray();
		return b;
	}

	private static <T extends Serializable> ByteArrayOutputStream serialize(T obj, boolean compressed)
			throws IOException {
		ByteArrayOutputStream buf = new ByteArrayOutputStream();
		ObjectOutputStream oos = null;
		try {
			if (compressed)
				oos = new ObjectOutputStream(new GZIPOutputStream(buf));
			else
				oos = new ObjectOutputStream(buf);
			oos.writeObject(obj);
		} finally {
			if (oos != null)
				oos.close();
		}
		return buf;
	}

	public static <T extends Serializable> T getObject(byte[] b) throws IOException,
			ClassNotFoundException {
		return deserialize(b, false);
	}

	public static <T extends Serializable> T getCompressedObject(byte[] b) throws IOException,
			ClassNotFoundException {
		return deserialize(b, true);
	}

	private static <T extends Serializable> T deserialize(byte[] data, boolean compressed)
			throws IOException, ClassNotFoundException {
		ByteArrayInputStream in = new ByteArrayInputStream(data);
		ObjectInputStream ois = null;
		try {
			if (compressed)
				ois = new ObjectInputStream(new GZIPInputStream(in));
			else
				ois = new ObjectInputStream(in);
			return (T) ois.readObject();
		} finally {
			IOUtils.close(ois);
		}
	}

你可能感兴趣的:(java对象序列化)