压缩
public class ZipUtilt {
public static boolean toZip(ServletResponse response, String filePath) {
try {
File file = new File(filePath);
OutputStream baseOS = response.getOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(baseOS);
boolean isSuccess=fileToZip(file, zipOutputStream, "");
zipOutputStream.flush();
zipOutputStream.close();
baseOS.flush();
baseOS.close();
return isSuccess;
} catch (Exception e) {
return false;
}
}
public static boolean fileToZip(File file, ZipOutputStream zipOutputStream, String zipEntryName) throws Exception {
if (file.isFile()) {
if(zipEntryName.isEmpty()) {
zipEntryName = file.getName().replaceAll("\\\\", "/");
}else {
zipEntryName = zipEntryName + "/" + file.getName().replaceAll("\\\\", "/");
}
InputStream baseIS = new FileInputStream(file);
ZipEntry zipEntry=new ZipEntry(zipEntryName);
zipOutputStream.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int lengeth;
while ((lengeth = baseIS.read(bytes)) != -1) {
zipOutputStream.write(bytes, 0, lengeth);
}
baseIS.close();
zipOutputStream.flush();
zipOutputStream.closeEntry();
return true;
} else {
if(zipEntryName.isEmpty()) {
zipEntryName = file.toString().substring(file.toString().replaceAll("\\\\", "/").lastIndexOf("/") + 1);
}else {
zipEntryName = zipEntryName + "/"+ file.toString().substring(file.toString().replaceAll("\\\\", "/").lastIndexOf("/") + 1);
}
File[] files = file.listFiles();
if (files == null || files.length == 0) {
if (true) {
zipOutputStream.putNextEntry(new ZipEntry(zipEntryName + "/"));
zipOutputStream.closeEntry();
}
} else {
zipOutputStream.putNextEntry(new ZipEntry(zipEntryName + "/"));
for (File contentFile : files) {
fileToZip(contentFile, zipOutputStream, zipEntryName);
}
}
return true;
}
}
}
解压
public class ZipUtilt {
public static void zipToFile(String zipPath){
try {
InputStream fileImputStream = new FileInputStream(zipPath);
String encoding = System.getProperty("file.encoding");
ZipInputStream zipInputStream = new ZipInputStream(fileImputStream, Charset.forName(encoding));
ZipEntry zipentry = null;
while ((zipentry =zipInputStream.getNextEntry())!=null){
String filePath = zipPath.substring(0,zipPath.indexOf("."))+"/"+zipentry.getName();
File file = FileUtils.getFile(filePath);
if (zipentry.isDirectory()){
if (!file.exists()){
file.mkdirs();
}else {
return;
}
}else {
if (!file.exists()){
File parentFile = file.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
byte[] bytes = new byte[1024];
int length = -1;
while ((length=zipInputStream.read(bytes))!=-1){
fileOutputStream.write(bytes,0,length);
}
}else {
return;
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
zipToFile("E:/Project/java是世界上最好的语言.zip");
}
}