Files
geg-gas-pcitc/itc-pcitc-dependencies/itc-pcitc-dependencies-service/src/main/java/com/pictc/utils/ObjectUtils.java
2025-12-02 10:21:46 +08:00

97 lines
2.2 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.pictc.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
/**
* @Description TODO(这里用一句话描述这个类的作用)
* @author zhangfucai
* @Date 2023年4月25日 上午12:49:14
* @version 1.0.0
*/
public class ObjectUtils {
private ObjectUtils() {
super();
}
public static byte[] toBytes(Object obj){
if(obj!=null) {
if(!(obj instanceof Serializable)) {
throw new RuntimeException(obj+"没有实现 Serializable");
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oo=null;
try {
oo = new ObjectOutputStream(out);
oo.writeObject(obj);
oo.flush();
return out.toByteArray();
} catch (Exception e) {
throw new RuntimeException("对象序列化失败!",e);
}finally {
closeQuietly(oo,out);
}
}
return null;
}
public static void write(OutputStream out,Object obj) {
if(obj!=null) {
if(!(obj instanceof Serializable)) {
throw new RuntimeException(obj+"没有实现 Serializable");
}
ObjectOutputStream oo=null;
try {
oo = new ObjectOutputStream(out);
oo.writeObject(obj);
oo.flush();
} catch (Exception e) {
throw new RuntimeException("对象序列化失败!",e);
}finally {
closeQuietly(oo,out);
}
}
}
@SuppressWarnings("unchecked")
public static <T>T reader(InputStream in){
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(in);
return (T) ois.readObject();
} catch (Exception e) {
throw new RuntimeException("对象反序列化失败!",e);
}finally {
closeQuietly(ois,in);
}
}
public static <T>T reader(byte[] bytes){
return reader(new ByteArrayInputStream(bytes));
}
public static void closeQuietly(Closeable... closeables) {
if (closeables == null)
return;
for (Closeable closeable : closeables) {
if (closeable == null)
return;
try {
closeable.close();
} catch (IOException ignored) {
}
}
}
}