您的位置:首页 > 编程语言 > Java开发

java解压缩文件

2015-09-07 11:22 525 查看
压缩:

// 压缩
public static void zip(String zipFileName, String inputFile)
throws Exception
{
File f = new File(inputFile);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
zip(out, f, null);
System.out.println("zip done");
out.close();
}

// 压缩
private static void zip(ZipOutputStream out, File f, String base)
throws Exception
{
if (f.isDirectory())
{
File[] fc = f.listFiles();
if (base != null)
out.putNextEntry(new ZipEntry(base + "/"));
base = base == null ? "" : base + "/";
for (int i = 0; i < fc.length; i++)
{
if (fc[i].getName().endsWith(".vmb"))
{
continue;
}
else
{
zip(out, fc[i], base + fc[i].getName());
}

}
}
else
{
out.putNextEntry(new ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int b;
while ((b = in.read()) != -1)
out.write(b);
in.close();
}
}


解压:
// 解压
public static void unZipFiles(String filePath, String directoryPath)
{
try
{
File filezip = new File(filePath);
ZipFile zipFile = new ZipFile(filezip);

Enumeration enu = zipFile.entries();
String result = "";
while (enu.hasMoreElements())
{
ZipEntry entry = (ZipEntry)enu.nextElement();
String name = entry.getName();
// 如果解压entry是目录,直接生成目录即可,不用写入,如果是文件,要讲文件写入
String path = directoryPath + File.separator + name;
result = result + path + "<br/>";
File file = new File(path);
if (entry.isDirectory())
{
file.mkdirs();
}
else
{
// 建议使用如下方式创建 流,和读取字节,不然会有乱码(当然要根据具体环境来定)
InputStream is = zipFile.getInputStream(entry);
byte[] buf1 = new byte[1024];
int len;
if (!file.exists())
{
file.getParentFile().mkdirs();
file.createNewFile();
}
OutputStream out = new FileOutputStream(file);
while ((len = is.read(buf1)) > 0)
{
String buf = new String(buf1, 0, len);
out.write(buf1, 0, len);
}
is.close();
out.flush();
out.close();
}
}

}
catch (Exception e)
{
e.printStackTrace();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: