<span style="font-size:18px;">/** * lsz */ public final class ZipUtil { /** * 解压zip文件 * @param unZipfile * @param destFile */ public static void unZip(String unZipfile, String destFile) { FileOutputStream fileOut; File file; InputStream inputStream; byte[] buf = new byte[1024*4]; try { //生成一个zip的文件 ZipFile zipFile = new ZipFile(unZipfile, "GBK"); //遍历zipFile中所有的实体,并把他们解压出来 for (@SuppressWarnings("unchecked") Enumeration<ZipEntry> entries = zipFile.getEntries(); entries .hasMoreElements();) { ZipEntry entry = entries.nextElement(); //生成他们解压后的一个文件 file = new File(destFile+File.separator+entry.getName()); if (entry.isDirectory()) { file.mkdirs(); } else { // 如果指定文件的目录不存在,则创建之. File parent = file.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } //获取出该压缩实体的输入流 inputStream = zipFile.getInputStream(entry); fileOut = new FileOutputStream(file); int length = 0; //将实体写到本地文件中去 while ((length = inputStream.read(buf)) > 0) { fileOut.write(buf, 0, length); } fileOut.close(); inputStream.close(); } } zipFile.close(); //解压完后将原压缩文件删除 File zipfile = new File(unZipfile); if(zipfile.exists()){ zipfile.delete(); } } catch (IOException ioe) { ioe.printStackTrace(); } } /** * 一个文件夹压缩 * 压缩文件夹 * @param filepath * @param savepath * @throws Exception */ public static void toZip(String filepath,String savepath) throws Exception{ File file = new File(filepath); if(file.exists()){ //判断导出路径是否为空,如果为空,则将压缩包生成到当前路径下 if(StringUtils.isBlank(savepath)){ savepath = filepath+".zip"; }else{ savepath = savepath+".zip"; } ZipOutputStream outPut = new ZipOutputStream(new FileOutputStream(new File(savepath))); outPut.setEncoding("GBK");//设置编码 createZip(outPut,file.listFiles(),null); outPut.flush(); outPut.close(); }else{ //not found throw new RuntimeException("Err :not found file exception:"+filepath); } } private static void createZip(org.apache.tools.zip.ZipOutputStream outPut,File[] listFiles,String fuPath) throws Exception { for(File f : listFiles){ String name = fuPath==null?f.getName():fuPath+"/"+f.getName();; if(f.isDirectory()){ outPut.putNextEntry(new ZipEntry(name+"/")); createZip(outPut,f.listFiles(),name); }else{ outPut.putNextEntry(new ZipEntry(name)); InputStream is = new FileInputStream(f); byte[] bys = new byte[1024]; int len = 0; while((len = is.read(bys))!=-1) outPut.write(bys, 0, len); is.close(); outPut.flush(); } } } /* * 复制文件 只能使复制文件,不能复制文件夹 */ public static void fileChannelCopy(File fromfile, File tofile) { FileInputStream fi = null; FileOutputStream fo = null; FileChannel in = null; FileChannel out = null; try { fi = new FileInputStream(fromfile); fo = new FileOutputStream(tofile); in = fi.getChannel();//得到对应的文件通道 out = fo.getChannel();//得到对应的文件通道 in.transferTo(0, in.size(), out);//连接两个通道,并且从in通道读取,然后写入out通道 } catch (IOException e) { e.printStackTrace(); } finally { try { fi.close(); in.close(); fo.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } }</span>
时间: 2024-10-29 10:48:47