- 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();
- }
-
-
- }
复制代码 |
|