编程解决Linux下解压zip乱码问题


JDK7 的ZipInputStream新添了一个构造方法,第二个参数可以指定字符集。这样一来我们就能用这个类写一个解压程序解决zip乱码问题了。

下面是代码:

package cn.fh;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class App {
 public static void main(String[] args) throws IOException {
  // parameter checking
  if (args.length >= 1) {
   System.out.println("opening file:" + args[0]);
   unzip(args[0]);
  } else {
   System.out.println("Please specify the name of the file that you want to uncompress.");
  }
 }
 
 public static void unzip(String fileName) throws IOException {
  ZipInputStream zin = new ZipInputStream(new FileInputStream(fileName), Charset.forName("GB2312"));
  ZipEntry en = null;
  FileOutputStream fos = null;
  File file = null;
 
  while ((en = zin.getNextEntry()) != null) {
   if (true == en.isDirectory()) {
    System.out.println("mkdir " + en.getName());
    file = new File(en.getName());
    file.mkdir();
   } else {
    System.out.println("extracting file " + en.getName());
    fos = new FileOutputStream(en.getName());
   
    byte[] buf = new byte[2048];
    int len = 0;
    while ((len = zin.read(buf, 0, buf.length)) != -1) {
     fos.write(buf, 0, len);
    }
    fos.close();
   }
   
   zin.closeEntry();
  }
 
  zin.close();
 }
}

大家可以直接复制上面的代码然后编译运行。也可以从我的GitHub仓库中clone一个maven项目下来:

git clone git@github.com:bkjia/unzip.git junzip

执行

mvn clean package

进行打包,然后

java -jar unzip-1.0-SNAPSHOT.jar [zip文件名]

程序会将zip直接解压到当前目录中。

另外也可以直接从帮客之家下载打好包的程序:

------------------------------------------分割线------------------------------------------

免费下载地址在 http://linux.bkjia.com/

用户名与密码都是www.bkjia.com

具体下载目录在 /2014年资料/9月/17日/编程解决Linux下解压zip乱码问题

下载方法见

------------------------------------------分割线------------------------------------------

本文永久更新链接地址:

相关内容

    暂无相关文章