歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 編程解決Linux下解壓zip亂碼問題

編程解決Linux下解壓zip亂碼問題

日期:2017/3/1 9:39:49   编辑:Linux編程

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 [email protected]:linuxidc/unzip.git junzip

執行

mvn clean package

進行打包,然後

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

程序會將zip直接解壓到當前目錄中。

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

------------------------------------------分割線------------------------------------------

免費下載地址在 http://linux.linuxidc.com/

用戶名與密碼都是www.linuxidc.com

具體下載目錄在 /2014年資料/9月/17日/編程解決Linux下解壓zip亂碼問題

下載方法見 http://www.linuxidc.com/Linux/2013-07/87684.htm

------------------------------------------分割線------------------------------------------

Copyright © Linux教程網 All Rights Reserved