JAVA解压zip压缩文件的实例

今天在弄一个东西,需要在PL/SQL中解压zip的压缩包,刚开始的时候是想着直接在PLSQL中调用java,在java里面调用unzip的shell命令来解析压缩文件,但是比较悲剧,一直老是失败,在尝试很多次之后,只能使用JAVA的大招来解决了,就是直接在java里面解压zip压缩文件,这个是基于java最基本的类来实现的。

具体代码:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnZip
{
private static final int buffer = 2048;

public static void unZip(String path)
{
int count = -1;
int index = -1;
String savepath = “”;
boolean flag = false;

//这里的\\根据系统不同,需要改变window是\\,linux是/
savepath = path.substring(0, path.lastIndexOf(“\\”)) + “\\”;
try
{
BufferedOutputStream bos = null;
ZipEntry entry = null;
FileInputStream fis = new FileInputStream(path);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));

while((entry = zis.getNextEntry()) != null) {
byte data[] = new byte[buffer];
String temp = entry.getName();
flag = isWantedFiles(temp);
if(!flag)
continue;
index = temp.lastIndexOf(“/”);
if(index > -1)
temp = temp.substring(index+1);
temp = savepath + temp;

File f = new File(temp);
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
bos = new BufferedOutputStream(fos, buffer);

while((count = zis.read(data, 0, buffer)) != -1) {
bos.write(data, 0, count);
}
bos.flush();
bos.close();
}
zis.close();
} catch (Exception e) {
e.printStackTrace();
}
}

//过滤自己想要的格式
public static boolean isWantedFiles(String filename){
boolean flag = false;
if(filename.endsWith(“.txt”)|| filename.endsWith(“.csv”)|| filename.endsWith(“.exc”))
flag = true;
return flag;
}
public static void main(String[] args) {
UnZip.unZip(“E:\\test\\test.zip”);
}
}

共有 0 条评论

Top