com.tukeof.common.util.SerializableUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of common-core Show documentation
Show all versions of common-core Show documentation
a common and useful pure java library
The newest version!
package com.tukeof.common.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class SerializableUtil {
public static byte[] toBytes(T obj)
throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream(128);
ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(obj);
oos.flush();
return baos.toByteArray();
}
}
public static byte[] toBytes(List objs)
throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream(128);
ObjectOutputStream oos = new ObjectOutputStream(baos)) {
for (T obj : objs) {
oos.writeObject(obj);
}
oos.flush();
return baos.toByteArray();
}
}
public static Object fromBytes(byte[] bytes)
throws IOException, ClassNotFoundException {
try (ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream(bytes))) {
return ois.readObject();
}
}
public static List