Java - 如何对 java 对象进行 Gzip 压缩
Java - How to do Gzip compression of java object
如何使用 Gzip 压缩 Java pojo 对象?
下面的代码压缩了一个字符串 -
public static String compress(String str, String inEncoding) {
if (str == null || str.length() == 0) {
return str;
}
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes(inEncoding));
gzip.close();
return URLEncoder.encode(out.toString("ISO-8859-1"), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
如何使用下面的pojoclass对象(Client cc)并压缩,而不是String str作为参数?
波乔class-
Class client {
Public string name;
Public string location;
//Getter and setter methods
}
我如何使用 gzip 压缩和解压缩此客户端 pojo class?
您可以通过执行以下操作压缩使用 gzip 实现可序列化的客户端 class:
public static bytes[] compressThis(Client client){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzipOut = new GZIPOutputStream(client);
ObjectOutputStream objectOut = new ObjectOutputStream(gzipOut);
objectOut.writeObject(client);
objectOut.close();
return baos.toByteArray();
}
接下来您可以通过执行以下操作来解压缩它:
public static getClientFrom(bytes[] bytes){
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
GZIPInputStream gzipIn = new GZIPInputStream(bais);
ObjectInputStream objectIn = new ObjectInputStream(gzipIn);
Client client = (Client) objectIn.readObject();
objectIn.close();
return client;
}
如何使用 Gzip 压缩 Java pojo 对象?
下面的代码压缩了一个字符串 -
public static String compress(String str, String inEncoding) {
if (str == null || str.length() == 0) {
return str;
}
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes(inEncoding));
gzip.close();
return URLEncoder.encode(out.toString("ISO-8859-1"), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
如何使用下面的pojoclass对象(Client cc)并压缩,而不是String str作为参数?
波乔class-
Class client {
Public string name;
Public string location;
//Getter and setter methods
}
我如何使用 gzip 压缩和解压缩此客户端 pojo class?
您可以通过执行以下操作压缩使用 gzip 实现可序列化的客户端 class:
public static bytes[] compressThis(Client client){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzipOut = new GZIPOutputStream(client);
ObjectOutputStream objectOut = new ObjectOutputStream(gzipOut);
objectOut.writeObject(client);
objectOut.close();
return baos.toByteArray();
}
接下来您可以通过执行以下操作来解压缩它:
public static getClientFrom(bytes[] bytes){
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
GZIPInputStream gzipIn = new GZIPInputStream(bais);
ObjectInputStream objectIn = new ObjectInputStream(gzipIn);
Client client = (Client) objectIn.readObject();
objectIn.close();
return client;
}