ZipEntry zipEntry = new ZipEntry(folder.substring(folder.lastIndexOf("\\")+1)+"\\"+filename + hz.substring(hz.lastIndexOf(".")));
//zip中添加文件夹,直接new ZipEntry("年度重大项目申请书\test.doc")
public boolean FoldersToZip(ArrayList<java.io.File> sourceFiles, String zipFilePath, String fileName, ArrayList<String> sourceFilesname) {
boolean flag = false;
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
ZipOutputStream zos = null;
if (sourceFiles == null || sourceFiles.size() == 0) {
Global.getInstance().LogApp("FoldersToZip-待压缩的文件不存在。");
} else {
try {
java.io.File zipFile = new java.io.File(zipFilePath + "/" + fileName);
if (zipFile.exists()) {
} else {
fos = new FileOutputStream(zipFile);
if(fos!=null){
CheckedOutputStream cos = new CheckedOutputStream(fos, new CRC32());
if(cos!=null){
zos = new ZipOutputStream(cos);
if(zos!=null){
zos.setEncoding("UTF-8");
byte[] bufs = new byte[1024 * 10];
for (int i = 0; i < sourceFiles.size(); i++) {
// 创建ZIP实体,并添加进压缩包
String hz = sourceFiles.get(i).getName();
String folder=sourceFiles.get(i).getParent();
String filename=sourceFilesname.get(i);
ZipEntry zipEntry = new ZipEntry(folder.substring(folder.lastIndexOf("\\")+1)+"\\"+filename + hz.substring(hz.lastIndexOf(".")));
if(zipEntry!=null){
zipEntry.setUnixMode(755);
zos.putNextEntry(zipEntry);
/*zos.putNextEntry(new ZipEntry("1/"));会在压缩文件中建立名字为1的文件夹,zos.putNextEntry(new ZipEntry("1/description.xml"));会在压缩文件中建立名字为1的文件夹中建立description.xml文件*/
// 读取待压缩的文件并写进压缩包里
if(sourceFiles.get(i).exists()){
fis = new FileInputStream(sourceFiles.get(i));
if(fis!=null){
bis = new BufferedInputStream(fis, 1024 * 10);
int read = 0;
while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
zos.write(bufs, 0, read);
}
}
}
}
}
flag = true;
}
}
}
}
} catch (FileNotFoundException e) {
Global.getInstance().LogError(e);
e.printStackTrace();
throw new RuntimeException(e);
} catch (IOException e) {
Global.getInstance().LogError(e);
e.printStackTrace();
throw new RuntimeException(e);
} finally {
// 关闭流
try {
if (null != bis)
bis.close();
if (null != zos)
zos.close();
} catch (IOException e) {
Global.getInstance().LogError(e);
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
return flag;
}