您的位置:首页 > 编程语言 > Java开发

java压缩文件ant.jar解决中文乱码

2013-10-25 17:06 666 查看
java压缩文件,网上找些例子,似乎只是压缩单个文件的,对目录下的所有文件进行压缩不行,

而且用java自带的Zip压缩的时候会中文路径出现乱码,而且不可以设置编码格式,后来又继

续查,查到用apache 的ant.jar可以解决中文路径乱码,而且还可以设置编码(ZipOutputStream.

setEncoding(encoding))。

下面是代码实现类:主要是对指定目录下的文件进行压缩(压缩完删除源文件,不需要可以注释掉相应的行代码) 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

public class Zip {
/**生成压缩包路径*/
public static File zipFile = null;
/**需要压缩的文件的根路径*/
public static File rootFile = null;
/**文件输出流对象*/
public static FileOutputStream fos = null;
/**压缩文件输出流对象*/
public static ZipOutputStream zos = null;
/**
* 关闭输入输出流
*/
public static void close(){
try {
if(zos!=null){
zos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fos!=null){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 初始化压缩文件路径,文件输出流,需要压缩文件的跟路径
* @param outPath 压缩包路径
*/
public static void init(String outPath){
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String dateDir = sdf.format(date);
rootFile = new File(outPath);
zipFile = new File("zip/"+dateDir+"update.zip");
try {
fos = new FileOutputStream(zipFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
zos = new ZipOutputStream(fos);

}
/**
* 压缩文件,压缩
* @param sourceFilePath 源文件路径
*/
public static void pack(String sourceFilePath){
/**文件夹路径*/
File sourceFile = new File(sourceFilePath);
/**文件列表*/
File[] sourceFiles = sourceFile.listFiles();
/**文件输入流*/
FileInputStream fis = null;
byte[] buf = new byte[1024];
for (int i = 0; i < sourceFiles.length; i++) {
// 创建ZIP实体,并添加进压缩包
if(sourceFiles[i].isDirectory()){		//是文件夹
pack(sourceFiles[i].getAbsolutePath());	//进入到文件夹中
//sourceFiles[i].delete();
}else{									//是文件,新建实体,压缩文件
String zipPath = sourceFiles[i].getAbsolutePath().replace(
rootFile.getAbsolutePath()+System.getProperty("file.separator"),"");
ZipEntry zipEntry = new ZipEntry(zipPath);
System.out.println("正在压缩-->"+zipEntry.getName());
try {
//添加实体
zos.putNextEntry(zipEntry);
// 读取待压缩的文件并写进压缩包里
fis = new FileInputStream(sourceFiles[i]);
int read = 0;
while ((read = fis.read(buf)) != -1) {
//写进压缩包
zos.write(buf, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
sourceFiles[i].delete();	//删除文件-压缩后文件会删除,不需要此行可以注释
}
}
}
sourceFile.delete();	//删除,当前文件目录-压缩源文件会删除,不需要可以注释掉此行

}
/**
* 测试
* @param args
*/
public static void main(String[] args) {
//注意outPath和sourcePath路径不要相同(一直循环)
String sourcePath = "G:/测试";
String outPath = "E:/";
//初始化
Zip.init(outPath);
//压缩
Zip.pack(sourcePath);
//关闭流
Zip.close();
}
}


注:源文件路径和压缩包路径不要相同,程序会一直执行

     ant.jar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  压缩 java 乱码 ant.jar
相关文章推荐