本文共 2344 字,大约阅读时间需要 7 分钟。
这几天做文件上传时遇到了解压缩的问题,就写了解压缩的功能实现,把代码贴出来,不过这里只能解压缩.zip后缀的文件。
package file; import java.util.zip. * ; // import java.io.InputStream; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; // import java.io.ByteArrayInputStream; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.logging. * ; import java.io.File; /** */ /** * 采用java.util.zip包来解压缩ZIP文件* 注意:在这段代码中我们用BufferedOutputStream代替了ZIPOutputStream。* ZIPOutputStream和GZIPOutputStream使用内置的512字节缓冲。* 当缓冲区的大小大于512字节时,使用BufferedOutputStream才是正确的* (例子中设置为2048)。ZIPOutputStream不允许你设置缓冲区的大小,* GZIPOutputStream也是一样,但创建GZIPOutputStream对象时* 可以通过构造函数的参数指定内置的缓冲尺寸。 */ public class MyUnzip ... { static Log log = LogFactory.getLog(MyUnzip.class); /** *//** * 解压缩 * * @param zipFile 当前解压缩的文件,这里包含全路径 * @param fullPath 要解压缩的位置,这里包含全路径 * @throws Exception */ public static void unzip(String zipFile, String fullPath)throws Exception ...{ // 读取压缩文件 BufferedInputStream bis = new BufferedInputStream(new FileInputStream( zipFile)); log.debug("read zip file : " + zipFile); ZipInputStream zin = new ZipInputStream(new BufferedInputStream(bis)); ZipEntry entry; File targetFold = null; try ...{ while ((entry = zin.getNextEntry()) != null) ...{ // 设置解压输出文件 int BUFFER = 2048; String tmp = fullPath + fileName + entry.getName(); //System.out.println("--"+tmp+" is dir:"+entry.isDirectory()); //create file targetFold = new File(tmp); if((!targetFold.exists() || targetFold.isFile())&&entry.isDirectory())...{ //(new File(tmp)).mkdirs(); targetFold.mkdirs(); } if(entry.isDirectory())...{ continue; } FileOutputStream fos = new FileOutputStream(targetFold); BufferedOutputStream dest = new BufferedOutputStream(fos,BUFFER); // 读取文件 int count = 0; byte[] data = new byte[BUFFER]; while ((count = zin.read(data, 0, BUFFER)) != -1) ...{ dest.write(data, 0, count); } dest.flush();// 刷新写入数据 dest.close();// 关闭输出流 } zin.close(); // 关闭输入流 } catch (Exception e) ...{ throw e; } } /** *//** * @param args */ public static void main(String[] args) ...{ String fullPath = "D:/brew/brew/data/upload/"; try ...{ //MyUnzip.MyUnzip("/test.zip", fullPath, fileName); String target = "D:/brew/brew/data/upload/upload.zip"; MyUnzip.unzip(target, fullPath); } catch (Exception e) ...{ e.printStackTrace(); } }} 转载地址:http://ubfmb.baihongyu.com/