今天做文件解压,学习了网上的代码后,模仿着写了一个,但是问题很头疼,报错找不到文件,然后用同样路径遍历,能遍历出文件,也试了别人的工具类,仍未解决问题,断点显示在new ZipFile(String path)时报错,下面贴完整代码:
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
-
@author zy 2017/5/18
*/
public class Unzip {
public void DataHandle(String unzipPath) {
final int SIZE = 2048;
String savepath = unzipPath.substring(0, unzipPath.lastIndexOf(".")) + File.separator;
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
ZipFile zipFile = null;
File unzipDir = new File(savepath);
if (!unzipDir.exists()) {
unzipDir.mkdirs();
}
try {
zipFile = new ZipFile(unzipPath);
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
byte buffer[] = new byte[SIZE];
ZipEntry entry = (ZipEntry) entries.nextElement();
String filename = entry.getName();
boolean ismkdir = false;
if (filename.lastIndexOf("/") != -1) {
ismkdir = true;
}
filename = savepath + filename;
File file = null;
if (entry.isDirectory()) {
file = new File(filename);
file.mkdirs();
continue;
}
file = new File(filename);
if (file.exists()) {
if (ismkdir) {
new File(filename.substring(0, filename.lastIndexOf("/"))).mkdirs();
}
}
file.createNewFile();
inputStream = zipFile.getInputStream(entry);
fileOutputStream = new FileOutputStream(file);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream, SIZE);
int count;
while ((count = inputStream.read(buffer)) > -1) {
bufferedOutputStream.write(buffer, 0, count);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
fileOutputStream.close();
}
zipFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (bufferedOutputStream != null) {
bufferedOutputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
if (zipFile != null) {
zipFile.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}public static void main(String[] args) {
Unzip unzip = new Unzip();
unzip.DataHandle(new String("E:"+File.separator+"test"+File.separator+"www.zip"));
}
}