黑马程序员技术交流社区
标题:
关于文件的压缩和解压的工具类
[打印本页]
作者:
qq272936993
时间:
2014-11-13 20:30
标题:
关于文件的压缩和解压的工具类
public class FileUtil {
public static byte[] readFile(String filePath ) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
return null;
}
FileChannel channel = new RandomAccessFile(file, "r").getChannel();
int size = (int) channel.size();
ByteBuffer bf = ByteBuffer.allocate(size);
channel.read(bf);
bf.flip();
channel.close();
return bf.array();
}
public static final byte [] compress(byte[] val) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream( val.length );
GZIPOutputStream gos = new GZIPOutputStream( bos );
gos.write( val, 0, val.length );
gos.finish();
gos.close();
// store it and set compression flag
return bos.toByteArray();
}
public static final byte [] unCompress(byte[] buf) throws IOException {
GZIPInputStream gzi = new GZIPInputStream( new ByteArrayInputStream( buf ) );
ByteArrayOutputStream bos = new ByteArrayOutputStream( buf.length );
int count;
byte[] tmp = new byte[buf.length];
while ( (count = gzi.read(tmp)) != -1 ) {
bos.write( tmp, 0, count );
}
// store uncompressed back to buffer
gzi.close();
return bos.toByteArray();
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2