黑马程序员技术交流社区

标题: 关于文件的压缩和解压的工具类 [打印本页]

作者: qq272936993    时间: 2014-11-13 20:30
标题: 关于文件的压缩和解压的工具类
  1. public class FileUtil {
  2.        
  3.         public static byte[] readFile(String filePath ) throws IOException {
  4.                 File file = new File(filePath);
  5.                 if (!file.exists()) {
  6.                         return null;
  7.                 }
  8.                 FileChannel channel = new RandomAccessFile(file, "r").getChannel();
  9.                 int size = (int) channel.size();
  10.                 ByteBuffer bf = ByteBuffer.allocate(size);
  11.                 channel.read(bf);
  12.                 bf.flip();
  13.                 channel.close();
  14.                 return bf.array();
  15.         }
  16.        
  17.         public static final byte [] compress(byte[] val) throws IOException {
  18.                 ByteArrayOutputStream bos = new ByteArrayOutputStream( val.length );
  19.                 GZIPOutputStream gos = new GZIPOutputStream( bos );
  20.                 gos.write( val, 0, val.length );
  21.                 gos.finish();
  22.                 gos.close();
  23.                
  24.                 // store it and set compression flag
  25.                 return  bos.toByteArray();               
  26.         }
  27.        
  28.         public static final byte [] unCompress(byte[] buf) throws IOException {
  29.                 GZIPInputStream gzi = new GZIPInputStream( new ByteArrayInputStream( buf ) );
  30.                 ByteArrayOutputStream bos = new ByteArrayOutputStream( buf.length );
  31.                
  32.                 int count;
  33.                 byte[] tmp = new byte[buf.length];
  34.                 while ( (count = gzi.read(tmp)) != -1 ) {
  35.                         bos.write( tmp, 0, count );
  36.                 }

  37.                 // store uncompressed back to buffer               
  38.                 gzi.close();
  39.                 return bos.toByteArray();
  40.         }
  41.        
  42.        
  43. }
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2