API练习 待扩充..
程序员文章站
2024-03-14 17:36:10
...
JAVA是很强大的,而这种强大很大程度上得益于JAVA强大的类库。API调用不可耻!可耻的是调用API都不会!
package com.gzip.demo;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* gzip压缩与解压缩,同时结合BASE64输出加密密文
*
*/
public class TestGzip {
/**
* gzip压缩
*/
public static byte[] compress(String str, String encoding) {
if (str == null || str.length() == 0) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip;
try {
gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes(encoding));
gzip.close();
} catch ( Exception e) {
e.printStackTrace();
}
return out.toByteArray();
}
/**
* gzip解压缩
* TODO read的字节数可能大于字节数组的大小,待完善
*/
public static byte[] uncompress(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
try {
GZIPInputStream ungzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = ungzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
} catch (Exception e) {
e.printStackTrace();
}
return out.toByteArray();
}
/**
* gzip+base64 返回舒服的英文加密串
*
*/
public static String compressToString(String str, String encoding) {
if (str == null || str.length() == 0) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip;
try {
gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes(encoding));
gzip.close();
} catch ( Exception e) {
e.printStackTrace();
}
return new BASE64Encoder().encode(out.toByteArray());
}
/**
* 解密并解压缩加密后的压缩数据
*
*/
public static byte[] uncompressEncodedeString(String str) {
byte[] bytes= new BASE64Decoder().decodeBuffer(str);
if (bytes == null || bytes.length == 0) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
try {
GZIPInputStream ungzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = ungzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
} catch (Exception e) {
e.printStackTrace();
}
return out.toByteArray();
}
}
下一篇: nodejs 加密压缩文件,解密解压文件
推荐阅读
-
API练习 待扩充..
-
spark - DataFrame Api 练习 博客分类: spark DataFrame Api 练习
-
Hbase练习-常用API使用
-
hibernate01:简介、搭建、配置文件详解、API详解和CRM练习:保存客户
-
python练习题4.30找完数-待研究
-
hibernate01:简介、搭建、配置文件详解、API详解和CRM练习:保存客户
-
白月黑羽教python之API接口自动化:课后练习
-
Java API练习1
-
json转js与js转json以及练习了ajax-xhr/fetch异步通讯以及模块常识,其中Promise状态及Promise中的Fetch API部分暂时还没进行示例学习操作
-
python练习题4.30找完数-待研究