项目里面有一个接口要频繁的刷新数据,同时数据量有很大,为了优化传输速度和节省流量,决定使用传输二进制数据,并将数据进行ZLib压缩。这就需要APP端进行二进制数据的解析和对数据进行ZLib解压缩.
不多说了,具体代码如下:
//把文件转换成byte[]数组
//把文件转换成byte[]数组 byte[] bytes0 = FileUtils.toByteArray(getExternalFilesDir(null).getPath() + File.separator+byteImgName); //ZLib解压缩数据 byte[] bytes = ZLibUtils.decompress(bytes0);
FileUtils:
public class FileUtils{ /** * the traditional io way * @param filename * @return * @throws IOException */ public static byte[] toByteArray0(String filename) throws IOException{ File f = new File(filename); if(!f.exists()){ throw new FileNotFoundException(filename);} ByteArrayOutputStream bos = new ByteArrayOutputStream((int)f.length()); BufferedInputStream in = null; try{ in = new BufferedInputStream(new FileInputStream(f)); int buf_size = 1024; byte[] buffer = new byte[buf_size]; int len = 0; while(-1 != (len = in.read(buffer,0,buf_size))){ bos.write(buffer,0,len); } return bos.toByteArray(); }catch (IOException e) { e.printStackTrace(); throw e; }finally{ try{ in.close(); }catch(IOException e){ e.printStackTrace(); } bos.close();