设为首页 加入收藏

TOP

编程解决Linux下解压zip乱码问题
2014-11-23 20:28:57 来源: 作者: 【 】 浏览:20
Tags:编程 解决 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:linuxidc/unzip.git junzip


执行


mvn clean package


进行打包,然后


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


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


另外也可以直接从Linux公社下载打好包的程序


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


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


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


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Java TCP入门例子 下一篇Java实现表达式求值

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: