您的位置:首页 > 博客中心 > 网络系统 >

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

时间:2022-04-03 08:56

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

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

本类排行

今日推荐

热门手游