-1

我目前正在使用 Java/Android 开发一个允许用户压缩和解压缩文件的应用程序。起初,我开始研究文件大小,例如:

1Byte = 8Bits
1KB = 1024Byte
1MB = 1024KB
1GB = 1024MB
1TB = 1024GB
1PB = 1024TB
1EB = 1024PB
1ZB = 1024EB
1YB = 1024ZB

在我研究了这个之后,我研究并阅读了网上的一些文章,发现有两种类型的文件压缩(如果我错了,请纠正我):无损和有损。无损压缩意味着将文件压缩成较小的位而不会丢失任何单个文件,而有损压缩意味着在压缩文件时删除了重要文件。

我还读到压缩(运行长度编码方法)是这样的:

AAABBCCDFFFFEEEEH

对此:

3A2B2CD4F4EH  

这让我了解了压缩/解压缩如何在文件上工作。

我还在网上搜索了有一个用于在 java 上压缩文件的 API(也适用于 android),它是

java.util.zip

我还尝试了一些关于从各种有用的网站/论坛/等(包括 stackoverflow.com)压缩和解压缩文件的代码,这让我对这项研究有了经验。

我还阅读了有关数据压缩中使用的算法的信息

 Huffman encoding algorithm -  assigns a code to characters in a file based on how frequently those characters occur

run-length encoding - generates a two-part value for repeated characters: the first part specifies the number of times the character is repeated, and the second part identifies the character

Lempel-Ziv algorithm - converts variable-length strings into fixed-length codes that consume less space than the original strings.

现在,我需要知道如何使用 java.util.zip 编写压缩和解压缩文件的算法(我也不知道如何使用它。网上的教程对我不起作用:/)。winzip、winrar、压缩文件夹(windows)和androzip(android app)使用什么算法?有人请逐步教我(把我当作一个没有受过教育的人)关于 java.util.zip 的工作原理和不同的算法。对不起,长篇大论的人。感谢您未来的帮助和帖子(如果有的话)!

4

1 回答 1

0
public static final byte[] unzip(byte[] in) throws IOException {
// decompress using GZIPInputStream 
ByteArrayOutputStream outStream = 
  new ByteArrayOutputStream(EXPECTED_COMPRESSION_RATIO * in.length);

GZIPInputStream inStream = 
  new GZIPInputStream ( new ByteArrayInputStream(in) );

byte[] buf = new byte[BUF_SIZE];
while (true) {
  int size = inStream.read(buf);
  if (size <= 0) 
    break;
  outStream.write(buf, 0, size);
}
outStream.close();

return outStream.toByteArray();
}


public static final byte[] zip(byte[] in) {
try {
  // compress using GZIPOutputStream 
  ByteArrayOutputStream byteOut= 
    new ByteArrayOutputStream(in.length / EXPECTED_COMPRESSION_RATIO);

  GZIPOutputStream outStream= new GZIPOutputStream(byteOut);

  try {
    outStream.write(in);
  } catch (Exception e) {
    LOG.error("", e);
  }

  try {
    outStream.close();
  } catch (IOException e) {
      LOG.error("", e);
  }

  return byteOut.toByteArray();

} catch (IOException e) {
    LOG.error("", e);
  return null;
}
}
于 2012-06-05T04:39:50.817 回答