写在前面

 通过阅读本篇文章,那你可以学(liao)习(jie)在android中如何对数据进行压缩(String->byte[]),对文件进行压缩和解压缩。阅读本篇文章大约需要五到十分钟,本人菜鸟,希望多多交流。

对数据进行压缩

  1. 到7z 官网下载 最新的 sdk 文件。 传送门: http://www.7-zip.org/sdk.html 。

    1. 将我们需要的代码 cv 到我们项目中。路径:java/ servenZip

    1. 讲代码复制到我们项目中后,自己手写压缩 方法。
public byte[] lzmaZip(String xml) throws IOException{   BufferedInputStream inStream = new BufferedInputStream(new ByteArrayInputStream(xml.getBytes()));   ByteArrayOutputStream bos = new ByteArrayOutputStream();   boolean eos = true;   Encoder encoder = new Encoder();   encoder.SetEndMarkerMode(eos);   encoder.WriteCoderProperties(bos);   long fileSize = xml.length();   if (eos)   fileSize = -1;   for (int i = 0; i < 8; i++)   bos.write((int)(fileSize >>> (8 * i)) & 0xFF);   encoder.Code(inStream, bos, -1, -1, null);   return bos.toByteArray() ;
}   

*: Encoder 为 Compression / LZMA / Encoder .

  1. 对与 我们获得到的 byte [] ,我们肯定是持怀疑态度的。接下来我们就需要 通过 大神的项目 来验证我们的办法是否正确了。github:https://github.com/hzy3774/AndroidP7zip (不是本人),该大神通过c 代码,来实现 7z 解压缩。并且作者 很负责 很热心,我在这里 帮他打一个广告…. 手动笑脸 ☻。(大神的项目 c 使用的头文件 会使用到 ndk 版本位14以下的,所以 我最开始用 ndk16编译的时候 出现头文件丢失的情况。笔者运行时间:2017年12月4日 16:28:46)。

  2. 将我们获取的 byte [] 通过文件保存的方式保存到本地,并且后缀名 为7z.

try {byte[] ss = SevenZipUtil.lzmaZip("大吉大利,今晚吃鸡!随着最近几年健身热," +"鸡胸肉好像已经成了网红。中国人到底有多爱吃鸡肉?中国从什么开始流行吃鸡?" +"鸡肉又是怎么一步步登上餐桌的? ");createFileWithByte(ss);appUtils.logError("7z 压缩后:"+ Arrays.toString(ss));} catch (IOException e) {e.printStackTrace();}

byte [] 保存成文件

/*** 根据byte数组生成文件** @param bytes*            生成文件用到的byte数组*/private void createFileWithByte(byte[] bytes) {// TODO Auto-generated method stub/*** 创建File对象,其中包含文件所在的目录以及文件的命名*/File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "ds","two.7z");// 创建FileOutputStream对象FileOutputStream outputStream = null;// 创建BufferedOutputStream对象BufferedOutputStream bufferedOutputStream = null;try {// 如果文件存在则删除if (file.exists()) {file.delete();}// 在文件系统中根据路径创建一个新的空文件file.createNewFile();// 获取FileOutputStream对象outputStream = new FileOutputStream(file);// 获取BufferedOutputStream对象bufferedOutputStream = new BufferedOutputStream(outputStream);// 往文件所在的缓冲输出流中写byte数据bufferedOutputStream.write(bytes);// 刷出缓冲输出流,该步很关键,要是不执行flush()方法,那么文件的内容是空的。bufferedOutputStream.flush();} catch (Exception e) {// 打印异常信息e.printStackTrace();} finally {// 关闭创建的流对象if (outputStream != null) {try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}if (bufferedOutputStream != null) {try {bufferedOutputStream.close();} catch (Exception e2) {e2.printStackTrace();}}}}

保存到手机上 成功之后 ,我们使用 大神的apk ,寻找到该文件夹所在位置,进行解压。然后我们进入文件管理界面,寻找解压后的文件,查看文件内容,经过 验证,该方法 可行。所以在这里 做下 笔记。 也来 填充一下 自己博文 较少的情况。(实力太菜…)

最后加上 本人使用的 工具类 SevenZipUtil:

/*** 解压 7z文件* Created by pul on 2017/12/1.*/public class SevenZipUtil {private final String TAG = "SevenZipUtil";/*** 将字符串 压缩 转换为 byte 数组** @param xml* @return* @throws IOException*/public static byte[] lzmaZip(String xml) throws IOException {BufferedInputStream inStream = new BufferedInputStream(new ByteArrayInputStream(xml.getBytes()));ByteArrayOutputStream bos = new ByteArrayOutputStream();boolean eos = true;Encoder encoder = new Encoder();encoder.SetEndMarkerMode(eos);encoder.WriteCoderProperties(bos);long fileSize = xml.length();if (eos)fileSize = -1;for (int i = 0; i < 8; i++)bos.write((int) (fileSize >>> (8 * i)) & 0xFF);encoder.Code(inStream, bos, -1, -1, null);return bos.toByteArray();}/*** 解压缩 7z文件*/public void extractile(String filepath) {RandomAccessFile randomAccessFile = null;IInArchive inArchive = null;try {randomAccessFile = new RandomAccessFile(filepath, "r");inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));// Getting simple interface of the archive inArchiveISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();Log.e(TAG,"  Hash  |  Size  | Filename");Log.e(TAG,"----------+------------+---------");for (final ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {final int[] hash = new int[]{0};if (!item.isFolder()) {ExtractOperationResult result;final long[] sizeArray = new long[1];result = item.extractSlow(new ISequentialOutStream() {public int write(byte[] data) throws SevenZipException {//Write to fileFileOutputStream fos;try {File file = new File(item.getPath());//error occours below
//                 file.getParentFile().mkdirs();fos = new FileOutputStream(file);fos.write(data);fos.close();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}hash[0] ^= Arrays.hashCode(data); // Consume datasizeArray[0] += data.length;return data.length; // Return amount of consumed data}});if (result == ExtractOperationResult.OK) {Log.e(TAG,String.format("%9X | %10s | %s", //hash[0], sizeArray[0], item.getPath()));} else {Log.e(TAG,"Error extracting item: " + result);}}}} catch (Exception e) {Log.e(TAG,"Error occurs: " + e);e.printStackTrace();System.exit(1);} finally {if (inArchive != null) {try {inArchive.close();} catch (SevenZipException e) {System.err.println("Error closing archive: " + e);}}if (randomAccessFile != null) {try {randomAccessFile.close();} catch (IOException e) {System.err.println("Error closing file: " + e);}}}}
}

Android 使用 7z 压缩字符串(工作总结)相关推荐

  1. Android集成7z极限压缩

    为什么使用7z压缩? 7z和其他压缩库相比拥有最大的压缩率,占用的磁盘空间最小,所以传输占用的带宽也就最小. 7z官方源码:https://sourceforge.net/projects/p7zip ...

  2. android bitmap string,Android Bitmap到Base64字符串(Android Bitmap to Base64 String)

    Android Bitmap到Base64字符串(Android Bitmap to Base64 String) 如何将一个大的Bitmap(用手机相机拍摄的照片)转换为Base64 String? ...

  3. JPEG压缩如何工作?

    转译自:https://www.impulseadventure.com/photo/jpeg-compression.html 当试图重新保存数码照片时,人们经常会面临使用"质量设置&qu ...

  4. linux rsync 原理,rsync压缩及其工作原理

    我使用rsync通过WebDav将大量文件(在Ubuntu Linux服务器上)备份到云网络服务.由于我的网络速度是我的瓶颈因素,我以为我会使用rsync -z(压缩)来减小文件大小,希望这可以减少瓶 ...

  5. android .rar,手机压缩文档不用愁:RAR for Android

    前言 如果在 PC 端遇到需要压缩文档的时候,估摸着大部分朋友会跟笔者我一样,首先会想到的工具就是:WinRAR,以至于不少电脑老鸟都记不得曾经有一个叫做 WinZip 的老大哥压缩工具的存在,谁叫r ...

  6. 字符串压缩 java_如何在Java中压缩字符串?

    如何在Java中压缩字符串? 我使用GZIPOutputStream或ZIPOutputStream压缩字符串(我的2222235278130938882小于20),但压缩结果比原始字符串长. 在某个 ...

  7. android camera(二):摄像头工作原理、s5PV310 摄像头接口(CAMIF)

    关键词: android  camera CMM 模组 camera参数  CAMIF 平台信息: 内核: linux 系统: android 平台:S5PV310(samsung exynos 42 ...

  8. android 查找字符在字符串的位置

    昨天,自己用到在字符串内查找一个字符串的位置,主要用到了  indexOf()的代码,这个是判断字符在字符串的第一次出现的位置.今天,自己没有什么好写的,所以决定把这个记录一下.也是很有用的. J ...

  9. 443. 压缩字符串

    443. 压缩字符串 给你一个字符数组 chars ,请使用下述算法压缩: 从一个空字符串 s 开始.对于 chars 中的每组 连续重复字符 : 如果这一组长度为 1 ,则将字符追加到 s 中. 否 ...

最新文章

  1. 我在MongoDB年终大会上获二等奖文章:由数据迁移至MongoDB导致的数据不一致问题及解决方案...
  2. JZOJ 4673. 4504. 5635. 【NOI2018模拟4.7】LCS
  3. windows拾取像素坐标_窗口坐标获取 windows
  4. 如何理解 Graph Convolutional Network (GCN)?
  5. 实现网站验证码切换功能
  6. 笔吧评测室所用测试软件,这是一台假游戏本:笔吧评测室 GIGABYTE 技嘉 Aero15 Classic-XA 游戏本 测评...
  7. #2002 - 服务器没有响应 (or the local MySQL server's socket is not ...
  8. DCTDAO将于3月27日在TrustSwap发行代币DCTD
  9. shell-最近7天目录
  10. C#之json序列化与反序列化
  11. VLAN中tagged与untagged的处理
  12. mysql数据库在哪里写语句_MySQL数据库基本操作以及SQL语句
  13. image not loaded  try to open it externally to fix format problem
  14. 电梯plc的io分配_三菱Q系列PLC的io分配
  15. C++中string类下的begin,end,rbegin,rend的用法
  16. opencv模拟景深效果
  17. nginx安装配置、Nginx支持php
  18. 赵联松武汉大学计算机学院,武汉大学电气工程学院2018年优秀大学生暑期夏令.doc...
  19. (十三)有一点心动 - 6
  20. 姑苏寻古[小刚执笔]

热门文章

  1. 七自由度机械臂设计分析——待更新
  2. Flask入门教程—超详细
  3. MMpose代码讲解之关键点Heatmap可视化
  4. iPhone更换电池是原装还是第三方?先别着急决定,看完文章再给答案
  5. H2 数据库怎么导出和导入
  6. Netty网络编程实战2,使用Netty开发聊天室功能
  7. Intriguing properties of neural networks手动翻译
  8. android显示大图片
  9. 总结整理Echarts双y轴曲线图(全)
  10. 使用什么软件可以将PDF文件进行编辑