importjava.io.ByteArrayInputStream;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.RandomAccessFile;importjava.util.zip.GZIPInputStream;importjava.util.zip.GZIPOutputStream;/*** 字符串的压缩
*@paramstr 待压缩的字符串
*@return返回压缩后的字符串
*@throwsIOException*/
public classGZIP {/*** 字符串的压缩
*
*@paramstr
* 待压缩的字符串
*@return返回压缩后的字符串
*@throwsIOException*/
public static String compress(String str) throwsIOException {if (null == str || str.length() <= 0) {returnstr;
}//创建一个新的 byte 数组输出流
ByteArrayOutputStream out = newByteArrayOutputStream();//使用默认缓冲区大小创建新的输出流
GZIPOutputStream gzip = newGZIPOutputStream(out);//将 b.length 个字节写入此输出流
gzip.write(str.getBytes());
gzip.close();//使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串
return out.toString("ISO-8859-1");
}/*** 字符串的解压
*
*@paramstr
* 对字符串解压
*@return返回解压缩后的字符串
*@throwsIOException*/
public static String unCompress(String str) throwsIOException {if (null == str || str.length() <= 0) {returnstr;
}//创建一个新的 byte 数组输出流
ByteArrayOutputStream out = newByteArrayOutputStream();//创建一个 ByteArrayInputStream,使用 buf 作为其缓冲区数组
ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));//使用默认缓冲区大小创建新的输入流
GZIPInputStream gzip = newGZIPInputStream(in);byte[] buffer = new byte[256];int n = 0;while ((n = gzip.read(buffer)) >= 0) {//将未压缩数据读入字节数组//将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此 byte数组输出流
out.write(buffer, 0, n);
}//使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串
return out.toString("UTF-8");
}public static voidWriteStringToFile(String filePath, String str) {try{
RandomAccessFile rf= new RandomAccessFile(filePath, "rw");
rf.writeBytes(str);
rf.close();
}catch(IOException e) {
e.printStackTrace();
}
}public static void main(String[] args) throwsIOException {
String str= "[{\"alias\":\"brownHorse\",\"level\":3,\"reward\":18,\"runSpeed\":1.0,\"speciesId\":1,\"uuid\":\"26CB848557CE4757B7D8D80C21730E55\"},{\"alias\":\"brownHorse\",\"level\":3,\"reward\":60,\"runSpeed\":1.0,\"speciesId\":1,\"uuid\":\"7529DAAC831E461D8AE68FBE71891BB7\"},{\"alias\":\"blackHorse\",\"level\":1,\"reward\":116,\"runSpeed\":2.0,\"speciesId\":2,\"uuid\":\"50AA595A6F3F424DA176478CC9A2FB81\"},{\"alias\":\"blackHorse\",\"level\":1,\"reward\":151,\"runSpeed\":2.0,\"speciesId\":2,\"uuid\":\"A8E54431AEAD48B4A5B5C9C5271BC741\"},{\"alias\":\"redHorse\",\"level\":1,\"reward\":286,\"runSpeed\":3.0,\"speciesId\":3,\"uuid\":\"CFA98753E51D45CFA0789C819CB5D51B\"},{\"alias\":\"redHorse\",\"level\":1,\"reward\":232,\"runSpeed\":3.0,\"speciesId\":3,\"uuid\":\"953C03AB07FF4495836DD4FDAE992E16\"}]";
String res=compress(str);
System.out.println(res);
System.out.println(res.length());
System.out.println(unCompress(res));
WriteStringToFile("d://a.txt", res);
}
}