如果需要下载的文件有很多是中文名的,解压时有中文名的文件出现乱码,试了很多方法不能解决问题。据说有一个Java插件包,用这个插件包可以解决中文名乱码的问题,但不知解压的文件是否要用它提供的类压缩后的文件,是否能解决用rar工具压缩的有中文名的文件,这个还没有试过。
参考资料:@1.http://www.oschina.net/code/snippet_4873_4142
@2.http://www.cnblogs.com/tnxk/archive/2011/09/22/2185248.html
/**
* 解压缩一个文件
*
* @param zipFile
* 压缩文件
* @param folderPath
* 解压缩的目标目录
* @throws IOException
* 当解压缩过程出错时抛出
*/
public static void upZipFile(File zipFile, String folderPath)
throws ZipException, IOException {
File desDir = new File(folderPath);
if (!desDir.exists()) {
desDir.mkdirs();
}
ZipFile zf = new ZipFile(zipFile);
for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
ZipEntry entry = ((ZipEntry) entries.nextElement());
InputStream in = zf.getInputStream(entry);
String str = folderPath;
// str = new String(str.getBytes("8859_1"), "GB2312");
File desFile = new File(str, java.net.URLEncoder.encode(
entry.getName(), "UTF-8"));
if (!desFile.exists()) {
File fileParentDir = desFile.getParentFile();
if (!fileParentDir.exists()) {
fileParentDir.mkdirs();
}
}
OutputStream out = new FileOutputStream(desFile);
byte buffer[] = new byte[1024 * 1024];
int realLength = in.read(buffer);
while (realLength != -1) {
out.write(buffer, 0, realLength);
realLength = in.read(buffer);
}
out.close();
in.close();
}
}
/**
* 解压缩一个文件
*
*/
public static void Unzip(String zipFile, String targetDir) {
int BUFFER = 4096; // 这里缓冲区我们使用4KB,
String strEntry; // 保存每个zip的条目名称
try {
BufferedOutputStream dest = null; // 缓冲输出流
FileInputStream fis = new FileInputStream(zipFile);
ZipInputStream zis = new ZipInputStream(
new BufferedInputStream(fis));
ZipEntry entry; // 每个zip条目的实例
while ((entry = zis.getNextEntry()) != null) {
try {
int count;
byte data[] = new byte[BUFFER];
strEntry = entry.getName();
File entryFile = new File(targetDir + strEntry);
File entryDir = new File(entryFile.getParent());
if (!entryDir.exists()) {
entryDir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(entryFile);
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
zis.close();
} catch (Exception cwj) {
cwj.printStackTrace();
}
}
zip扮演着归档和压缩两个角色;gzip并不将文件归档,仅只是对单个文件进行压缩,所以,在UNIX平台上,命令tar通常用来创建一个档案文件,然后命令gzip来将档案文件压缩。
Java I/O类库还收录了一些能读写压缩格式流的类。要想提供压缩功能,只要把它们包在已有的I/O类的外面就行了。这些类不是Reader和Writer,而是InputStream和OutStreamput的子类。这是因为压缩算法是针对byte而不是字符的。
相关类与接口:
Checksum 接口:被类Adler32和CRC32实现的接口
Adler32 :使用Alder32算法来计算Checksum数目
CRC32 :使用CRC32算法来计算Checksum数目
CheckedInputStream :InputStream派生类,可得到输入流的校验和Checksum,用于校验数据的完整性
CheckedOutputStream :OutputStream派生类,可得到输出流的校验和Checksum, 用于校验数据的完整性
DeflaterOutputStream :压缩类的基类。
ZipOutputStream :DeflaterOutputStream的一个子类,把数据压缩成Zip文件格式。
GZIPOutputStream :DeflaterOutputStream的一个子类,把数据压缩成GZip文件格式
InflaterInputStream :解压缩类的基类
ZipInputStream :InflaterInputStream的一个子类,能解压缩Zip格式的数据
GZIPInputStream :InflaterInputStream的一个子类,能解压缩Zip格式的数据
ZipEntry 类:表示 ZIP 文件条目