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

42 篇文章 0 订阅

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:wanghongfei/unzip.git junzip

执行

mvn clean package

进行打包,然后

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

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

另外也可以直接从百度云里下载打好包的程序:http://pan.baidu.com/s/1nthXjUp

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值