JAVA压缩文件夹包括里面的文件,可以设置压缩后的目录结构

package test.downloadzip;


/* 
 * 在进行压缩流操作时建议使用开源的类库org.apache.tools.zip.*, 
 * 不要用java.util.zip.*类库,这个在实现上没有前面那个做的完善。 
 */


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.TreeSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class ZipDemo {


public static TreeSet ts = new TreeSet();


public static void main(String[] args) throws IOException {
// 需要压缩的目录
File sFolder = new File("D:\\leo\\file\\pic");

// 压缩之后的目录,如果是网络下载情况可以将流写入response就好了
File zipFolder = new File("d:\\zipDown\\test.zip");


ZipFolderMethod(sFolder, zipFolder);


System.out.println("导出成功");


}


public static void ZipFolderMethod(File sFoder, File zipFolder) throws IOException {
// TODO Auto-generated method stub


ZipOutputStream zipoutFolder = new ZipOutputStream(new FileOutputStream(zipFolder));


InputStream in = null;


// zipoutFolder.setEncoding("GBK"); //为解决注释乱码
zipoutFolder.setComment("文件夹的压缩");


// 列出所有文件的路径,保存到集合中,在ListAllDirectory(sFoder)方法中用到递归
TreeSet pathTreeSet = ListAllDirectory(sFoder);


String[] pathStr = pathTreeSet.toString().substring(1, pathTreeSet.toString().length() - 1).split(",");


for (int i = 0; i < pathStr.length; i++) {
String filePath = pathStr[i].trim();
StringBuffer pathURL = new StringBuffer();
String[] tempStr = filePath.split("\\\\"); // 这个地方需要注意,在Java中需要“\\\\”表示“\”字符串。


// 这里的变量j是从第几层开始打压缩包
for (int j = 6; j < tempStr.length - 1; j++) {
pathURL.append(tempStr[j] + File.separator);
}
String path = pathURL.append(tempStr[tempStr.length - 1]).toString();


in = new FileInputStream(new File(filePath));


zipoutFolder.putNextEntry(new ZipEntry(path));


int temp = 0;
while ((temp = in.read()) != -1) {
zipoutFolder.write(temp);
}


in.close();
}
zipoutFolder.close();
}


public static TreeSet ListAllDirectory(File sFolder) {
if (sFolder != null) {
if (sFolder.isDirectory()) {
File f[] = sFolder.listFiles();
if (f != null) {
for (int i = 0; i < f.length; i++) {
ListAllDirectory(f[i]);
}
}
} else {
ts.add(sFolder.toString());
}
}
return ts;
}
}

你可能感兴趣的:(练习)