如果需要下载的文件有很多是中文名的,解压时有中文名的文件出现乱码,试了很多方法不能解决问题。据说有一个Java插件包,用这个插件包可以解决中文名乱码的问题,但不知解压的文件是否要用它提供的类压缩后的文件,是否能解决用rar工具压缩的有中文名的文件,这个还没有试过。 参考资料:@1.http://www.oschina.net/code/snippet_4873_4142 @2.http://www.cnblogs.com/tnxk/archive/2011/09/22/2185248.html -
-
-
-
-
-
-
-
-
-
-
- public static void upZipFile(File zipFile, String folderPath)
- throws ZipException, IOException {
- File desDir = new File(folderPath);
- if (!desDir.exists()) {
- desDir.mkdirs();
- }
- ZipFile zf = new ZipFile(zipFile);
- for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
- ZipEntry entry = ((ZipEntry) entries.nextElement());
- InputStream in = zf.getInputStream(entry);
- String str = folderPath;
-
- File desFile = new File(str, java.net.URLEncoder.encode(
- entry.getName(), "UTF-8"));
-
- if (!desFile.exists()) {
- File fileParentDir = desFile.getParentFile();
- if (!fileParentDir.exists()) {
- fileParentDir.mkdirs();
- }
- }
-
- OutputStream out = new FileOutputStream(desFile);
- byte buffer[] = new byte[1024 * 1024];
- int realLength = in.read(buffer);
- while (realLength != -1) {
- out.write(buffer, 0, realLength);
- realLength = in.read(buffer);
- }
-
- out.close();
- in.close();
-
- }
- }
-
-
-
-
- public static void Unzip(String zipFile, String targetDir) {
- int BUFFER = 4096;
- String strEntry;
- try {
- BufferedOutputStream dest = null;
- FileInputStream fis = new FileInputStream(zipFile);
- ZipInputStream zis = new ZipInputStream(
- new BufferedInputStream(fis));
- ZipEntry entry;
- while ((entry = zis.getNextEntry()) != null) {
- try {
- int count;
- byte data[] = new byte[BUFFER];
- strEntry = entry.getName();
- File entryFile = new File(targetDir + strEntry);
- File entryDir = new File(entryFile.getParent());
- if (!entryDir.exists()) {
- entryDir.mkdirs();
- }
- FileOutputStream fos = new FileOutputStream(entryFile);
- dest = new BufferedOutputStream(fos, BUFFER);
- while ((count = zis.read(data, 0, BUFFER)) != -1) {
-
- dest.write(data, 0, count);
- }
- dest.flush();
- dest.close();
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- zis.close();
- } catch (Exception cwj) {
- cwj.printStackTrace();
- }
- }
zip扮演着归档和压缩两个角色;gzip并不将文件归档,仅只是对单个文件进行压缩,所以,在UNIX平台上,命令tar通常用来创建一个档案文件,然后命令gzip来将档案文件压缩。 Java I/O类库还收录了一些能读写压缩格式流的类。要想提供压缩功能,只要把它们包在已有的I/O类的外面就行了。这些类不是Reader和Writer,而是InputStream和OutStreamput的子类。这是因为压缩算法是针对byte而不是字符的。
相关类与接口: Checksum 接口:被类Adler32和CRC32实现的接口 Adler32 :使用Alder32算法来计算Checksum数目 CRC32 :使用CRC32算法来计算Checksum数目 CheckedInputStream :InputStream派生类,可得到输入流的校验和Checksum,用于校验数据的完整性 CheckedOutputStream :OutputStream派生类,可得到输出流的校验和Checksum, 用于校验数据的完整性 DeflaterOutputStream :压缩类的基类。 ZipOutputStream :DeflaterOutputStream的一个子类,把数据压缩成Zip文件格式。 GZIPOutputStream :DeflaterOutputStream的一个子类,把数据压缩成GZip文件格式 InflaterInputStream :解压缩类的基类 ZipInputStream :InflaterInputStream的一个子类,能解压缩Zip格式的数据 GZIPInputStream :InflaterInputStream的一个子类,能解压缩Zip格式的数据 ZipEntry 类:表示 ZIP 文件条目 ZipFile 类:此类用于从 ZIP 文件读取条目
用GZIP进行对单个文件压缩
GZIP的接口比较简单,因此如果你只需对一个流进行压缩的话,可以使用它。当然它可以压缩字符流,与可以压缩字节流,下面是一个对GBK编码格式的文本文件进行压缩的。
压缩类的用法非常简单;只要用GZIPOutputStream 或ZipOutputStream把输出流包起来,再用GZIPInputStream 或ZipInputStream把输入流包起来就行了。剩下的都是些普通的I/O操作。 Java代码
- import java.io.BufferedOutputStream;
- import java.io.BufferedReader;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.zip.GZIPInputStream;
- import java.util.zip.GZIPOutputStream;
- public class GZIPcompress {
- public static void main(String[] args) throws IOException {
-
- BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("e:/tmp/source.txt"), "GBK"));
-
-
- BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream("test.txt.gz")));
- System.out.println("开始写压缩文件...");
- int c;
- while ((c = in.read()) != -1) {
-
-
-
-
- out.write(String.valueOf((char) c).getBytes("GBK"));
- }
- in.close();
- out.close();
- System.out.println("开始读压缩文件...");
-
- BufferedReader in2 = new BufferedReader(new InputStreamReader(
- new GZIPInputStream(new FileInputStream("test.txt.gz")), "GBK"));
- String s;
-
- while ((s = in2.readLine()) != null) {
- System.out.println(s);
- }
- in2.close();
- }
- }
使用Zip进行多个文件压缩 Java对Zip格式类库支持得比较全面,得用它可以把多个文件压缩成一个压缩包。这个类库使用的是标准Zip格式,所以能与很多的压缩工具兼容。 ZipOutputStream类有设置压缩方法以及在压缩方式下使用的压缩级别,zipOutputStream.setMethod(int method)设置用于条目的默认压缩方法。只要没有为单个 ZIP 文件条目指定压缩方法,就使用ZipOutputStream所设置的压缩方法来存储,默认值为 ZipOutputStream.DEFLATED(表示进行压缩存储),还可以设置成STORED(表示仅打包归档存储)。 ZipOutputStream在设置了压缩方法为DEFLATED后,我们还可以进一步使用setLevel(int level)方法来设置压缩级别,压缩级别值为0-9共10个级别(值越大,表示压缩越利害),默认为 Deflater.DEFAULT_COMPRESSION=-1。当然我们也可以通过条目ZipEntry的setMethod方法为单个条件设置压缩方法。
类ZipEntry描述了存储在ZIP文件中的压缩文件。类中包含有多种方法可以用来设置和获得ZIP条目的信息。类ZipEntry是被 ZipFile[zipFile.getInputStream(ZipEntry entry)]和ZipInputStream使用来读取ZIP文件,ZipOutputStream来写入ZIP文件的。有以下这些有用的方法:getName()返回条目名称、isDirectory()如果为目录条目,则返回 true(目录条目定义为其名称以 '/' 结尾的条目)、setMethod(int method) 设置条目的压缩方法,可以为 ZipOutputStream.STORED 或 ZipOutputStream .DEFLATED。
下面实例我们使用了apache的zip工具包(所在包为ant.jar ),因为java类型自带的不支持中文路径,不过两者使用的方式是一样的,只是apache压缩工具多了设置编码方式的接口,其他基本上是一样的。另外,如果使用org.apache.tools.zip.ZipOutputStream来压缩的话,我们只能使用 org.apache.tools.zip.ZipEntry来解压,而不能使用java.util.zip.ZipInputStream来解压读取了,当然apache并未提供ZipInputStream类。
转载代码: - import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.util.Enumeration;
- import java.util.zip.CRC32;
- import java.util.zip.CheckedInputStream;
- import java.util.zip.CheckedOutputStream;
- import java.util.zip.Deflater;
- import java.util.zip.ZipException;
- import java.util.zip.ZipInputStream;
- import org.apache.tools.zip.ZipEntry;
- import org.apache.tools.zip.ZipFile;
- import org.apache.tools.zip.ZipOutputStream;
-
-
-
-
-
-
- public class ZipCompress {
- private static boolean isCreateSrcDir = true;
-
-
-
-
- public static void main(String[] args) throws IOException {
- String src = "m:/新建文本文档.txt";
- String decompressDir = "e:/tmp/decompress";
- String archive = "e:/tmp/test.zip";
- String comment = "Java Zip 测试.";
-
- writeByApacheZipOutputStream(src, archive, comment);
-
-
-
-
-
-
- readByApacheZipFile(archive, decompressDir);
- }
-
-
- public static void writeByApacheZipOutputStream(String src, String archive, String comment) throws FileNotFoundException, IOException {
-
- FileOutputStream f = new FileOutputStream(archive);
-
- CheckedOutputStream csum = new CheckedOutputStream(f, new CRC32());
- ZipOutputStream zos = new ZipOutputStream(csum);
-
- zos.setEncoding("GBK");
- BufferedOutputStream out = new BufferedOutputStream(zos);
-
- zos.setComment(comment);
-
- zos.setMethod(ZipOutputStream.DEFLATED);
-
- zos.setLevel(Deflater.BEST_COMPRESSION);
- File srcFile = new File(src);
- if (!srcFile.exists() || (srcFile.isDirectory() && srcFile.list().length == 0)) {
- throw new FileNotFoundException("File must exist and ZIP file must have at least one entry.");
- }
-
- src = src.replaceAll("\\", "/");
- String prefixDir = null;
- if (srcFile.isFile()) {
- prefixDir = src.substring(0, src.lastIndexOf("/") + 1);
- } else {
- prefixDir = (src.replaceAll("/$", "") + "/");
- }
-
- if (prefixDir.indexOf("/") != (prefixDir.length() - 1) && isCreateSrcDir) {
- prefixDir = prefixDir.replaceAll("[^/]+/$", "");
- }
-
- writeRecursive(zos, out, srcFile, prefixDir);
- out.close();
-
- System.out.println("Checksum: " + csum.getChecksum().getValue());
- BufferedInputStream bi;
- }
转载代码: -
-
-
-
-
-
-
-
-
-
-
-
-
- public static void readByApacheZipFile(String archive, String decompressDir) throws IOException, FileNotFoundException, ZipException {
- BufferedInputStream bi;
- ZipFile zf = new ZipFile(archive, "GBK");
- Enumeration e = zf.getEntries();
- while (e.hasMoreElements()) {
- ZipEntry ze2 = (ZipEntry) e.nextElement();
- String entryName = ze2.getName();
- String path = decompressDir + "/" + entryName;
- if (ze2.isDirectory()) {
- System.out.println("正在创建解压目录 - " + entryName);
- File decompressDirFile = new File(path);
- if (!decompressDirFile.exists()) {
- decompressDirFile.mkdirs();
- }
- } else {
- System.out.println("正在创建解压文件 - " + entryName);
- String fileDir = path.substring(0, path.lastIndexOf("/"));
- File fileDirFile = new File(fileDir);
- if (!fileDirFile.exists()) {
- fileDirFile.mkdirs();
- }
- BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(decompressDir + "/" + entryName));
- bi = new BufferedInputStream(zf.getInputStream(ze2));
- byte[] readContent = new byte[1024];
- int readCount = bi.read(readContent);
- while (readCount != -1) {
- bos.write(readContent, 0, readCount);
- readCount = bi.read(readContent);
- }
- bos.close();
- }
- }
- zf.close();
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static void readByZipInputStream(String archive, String decompressDir) throws FileNotFoundException, IOException {
- BufferedInputStream bi;
-
- System.out.println("开始读压缩文件");
- FileInputStream fi = new FileInputStream(archive);
- CheckedInputStream csumi = new CheckedInputStream(fi, new CRC32());
- ZipInputStream in2 = new ZipInputStream(csumi);
- bi = new BufferedInputStream(in2);
- java.util.zip.ZipEntry ze;
-
- while ((ze = in2.getNextEntry()) != null) {
- String entryName = ze.getName();
- if (ze.isDirectory()) {
- System.out.println("正在创建解压目录 - " + entryName);
- File decompressDirFile = new File(decompressDir + "/" + entryName);
- if (!decompressDirFile.exists()) {
- decompressDirFile.mkdirs();
- }
- } else {
- System.out.println("正在创建解压文件 - " + entryName);
- BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(decompressDir + "/" + entryName));
- byte[] buffer = new byte[1024];
- int readCount = bi.read(buffer);
- while (readCount != -1) {
- bos.write(buffer, 0, readCount);
- readCount = bi.read(buffer);
- }
- bos.close();
- }
- }
-
- bi.close();
- System.out.println("Checksum: " + csumi.getChecksum().getValue());
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- private static void writeRecursive(ZipOutputStream zos,BufferedOutputStream bo,File srcFile, String prefixDir) throws IOException, FileNotFoundException {
- ZipEntry zipEntry;
- String filePath = srcFile.getAbsolutePath().replaceAll("\\", "/").replaceAll("
- if (srcFile.isDirectory()) {
- filePath = filePath.replaceAll("/$", "") + "/";
- }
- String entryName = filePath.replace(prefixDir, "").replaceAll("/$", "");
- if (srcFile.isDirectory()) {
- if (!"".equals(entryName)) {
- System.out.println("正在创建目录 - " + srcFile.getAbsolutePath() + " entry/");
- zos.putNextEntry(zipEntry);
- }
- File srcFiles[] = srcFile.listFiles();
- for (int i = 0; i < srcFiles.length; i++) {
- writeRecursive(zos, bo, srcFiles[i], prefixDir);
- }
- } else {
- System.out.println("正在写文件 - " + srcFile.getAbsolutePath() + " entrym:/新建文本文档.txt";
- String decompressDir = "e:/tmp/decompress";
- String archive = "e:/tmp/test.zip";
- String comment = "Java Zip 测试.";
-
- writeByApacheZipOutputStream(src, archive, comment);
-
-
-
-
-
-
- readByApacheZipFile(archive, decompressDir);
- }
- public static void writeByApacheZipOutputStream(String src, String archive, String comment) throws FileNotFoundException, IOException {
-
- FileOutputStream f = new FileOutputStream(archive);
-
- CheckedOutputStream csum = new CheckedOutputStream(f, new CRC32());
- ZipOutputStream zos = new ZipOutputStream(csum);
-
- zos.setEncoding("GBK");
- BufferedOutputStream out = new BufferedOutputStream(zos);
-
- zos.setComment(comment);
-
- zos.setMethod(ZipOutputStream.DEFLATED);
-
- zos.setLevel(Deflater.BEST_COMPRESSION);
- File srcFile = new File(src);
- if (!srcFile.exists() || (srcFile.isDirectory() && srcFile.list().length == 0)) {
- throw new FileNotFoundException("File must exist and ZIP file must have at least one entry.");
- }
-
-
-
- src = src.replaceAll("\\", "/");
- String prefixDir = null;
- if (srcFile.isFile()) {
- prefixDir = src.substring(0, src.lastIndexOf("/") + 1);
- } else {
- prefixDir = (src.replaceAll("/$", "") + "/");
- }
-
-
-
- if (prefixDir.indexOf("/") != (prefixDir.length() - 1) && isCreateSrcDir) {
- prefixDir = prefixDir.replaceAll("[^/]+/$", "");
- }
-
-
-
- writeRecursive(zos, out, srcFile, prefixDir);
- out.close();
-
- System.out.println("Checksum: " + csum.getChecksum().getValue());
- BufferedInputStream bi;
- }
要想把文件加入压缩包,你必须将ZipEntry对象传给putNextEntry( )。ZipEntry是一个接口很复杂的对象,它能让你设置和读取Zip文件里的某条记录的信息,这些信息包括:文件名,压缩前和压缩后的大小,日期,CRC校验码,附加字段,注释,压缩方法,是否是目录。虽然标准的Zip格式是支持口令的,但是Java的Zip类库却不支持。而且ZipEntry 却只提供了CRC的接口,而CheckedInputStream和CheckedOutputStream却支持Adler32和CRC32两种校验码。虽然这是底层的Zip格式的限制,但却妨碍了你使用更快的Adler32了。
要想提取文件,可以用ZipInputStream的getNextEntry( )方法。只要压缩包里还有ZipEntry,它就会把它提取出来。此外还有一个更简洁的办法,你可以用ZipFile对象去读文件。ZipFile有一个 entries()方法,它可以返回ZipEntries的Enumeration。然后通过zipFile. getInputStream(ZipEntry entry)获取压缩流就可以读取相应条目了。 要想读取校验码,必须先获取Checksum对象。我们这里用的是CheckedOutputStream和 CheckedInputStream,不过你也可以使用Checksum。java.util.zip包中比较重要校验算法类是Adler32和 CRC32,它们实现了java.util.zip.Checksum接口,并估算了压缩数据的校验和(checksum)。在运算速度方面,Adler32算法比CRC32算法要有一定的优势;但在数据可信度方面,CRC32算法则要更胜一筹。GetValue方法可以用来获得当前的 checksum值,reset方法能够重新设置checksum为其缺省的值。 校验和一般用来校验文件和信息是否正确的传送。举个例子,假设你想创建一个ZIP文件,然后将其传送到远程计算机上。当到达远程计算机后,你就可以使用checksum检验在传输过程中文件是否发生错误,有点像下载文件后我们可以使用哈希值来校验文件下载过程是否出错了。 Zip类里还有一个让人莫名其妙的setComment( )方法。如ZipCompress.java所示,写文件的时候,你可以加注释,但是读文件的时候,ZipInputSream却不提供接口。看来它的注释功能完全是针对条目的,是用ZipEntry实现的。 当然,GZIP和Zip不光能用来压缩文件——它还能压缩任何东西,包括要通过网络传输的数据。
|