java怎么判断上传的包是zip,java实现上传zip解压及判断压缩包文件夹功能

直接上Service,通过代码看思路贯穿整个功能,很多工具类可以复用,文件路径可以去看我博客里的

(使用ResourceBundle

url:

https://blog.csdn.net/qq_17025903/article/details/75949066

html页面ZIP:

页面jsfunction checkHostBatchRun(){ if(confirm("上传重名文件将会替换掉原有文件,是否继续上传?")){ //年 var hostYear=$("#hostYear").val(); //季度 var quarter=$("#hostQuarter").find("option:selected").text(); $.ajax({ type : "POST", cache : false, dataType : "json", data:new FormData($('#hostUploadForm')[0]), processData: false,//用于对data参数进行序列化处理 这里必须false contentType: false, //必须 ?hostYear="+hostYear+"&quarter="+quarter" url : "../uploadController/hostUploadZipBatchRun.htm?hostYear="+hostYear+"&&quarter="+quarter+" ", success : function(obj) { /* alert(obj.data.msg); */ var result=obj.data.msg; if(result==true){ $("#hostCheckResult").text("上传成功!").css("color","blue"); $("#hostRunResult").attr("disabled",false); }else{ $("#hostCheckResult").text("上传失败!").css("color","red"); } } }); } }

Service//创建解析器 MultipartHttpServletRequest mh=(MultipartHttpServletRequest) request; //获得文件 CommonsMultipartFile cmf=(CommonsMultipartFile) mh.getFile("hostFileBatch"); //获得原始文件名 String oriName=cmf.getOriginalFilename(); //拼接年+月 String path=hostYear.concat(quarter); //String path=String.valueOf(year).concat(String.valueOf(month)); String savePath=Commons.HOST_UPLOAD_PATH+"\\"+path; //保存的路径 //File storeDirectory=new File(savePath); //判断是不是zip文件 if(oriName.matches(".*.zip")) { //判断文件目录是否存在 File file=new File(savePath); //不存在 if(!file.exists()) { //创建文件夹 file.mkdirs(); }else { //文件存在则删除 deleteDir(file); //file.delete(); file.mkdirs(); //删除文件原始路径 int deletePath=uploadZipDao.deleteOldFile(oriName,savePath); } //获取文件 FileItem fileItem=cmf.getFileItem(); try { //解压文件到指定目录 FileUnZip.zipToFile(oriName, savePath); } catch (Exception e){ e.printStackTrace(); new File(savePath,oriName).delete(); } fileItem.delete(); //保存路径文件名 boolean result=addPath(oriName,savePath); if(result==true) { //执行批处理 return true; } return false; }else { //不是zip则返回false return false; } }

解压工具类package cn.secure.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipFile; public class FileUnZip { /** * 解压zip文件 * @author 于公成 * @param sourceFile,待解压的zip文件; * toFolder,解压后的存放路径 * @throws Exception **/ public static void zipToFile(String sourceFile, String toFolder) throws Exception { String toDisk = toFolder;// 接收解压后的存放路径 ZipFile zfile = new ZipFile(sourceFile, "gbk");// 连接待解压文件 "utf-8"会乱码 Enumeration zList = zfile.getEntries();// 得到zip包里的所有元素 ZipEntry ze = null; byte[] buf = new byte[1024]; while (zList.hasMoreElements()) { ze = (ZipEntry) zList.nextElement(); if (ze.isDirectory()) { // log.info("打开zip文件里的文件夹:"+ ze.getName() +"skipped..."); continue; } OutputStream outputStream = null; InputStream inputStream = null; try { // 以ZipEntry为参数得到一个InputStream,并写到OutputStream中 outputStream = new BufferedOutputStream(new FileOutputStream(getRealFileName(toDisk, ze.getName()))); inputStream = new BufferedInputStream(zfile.getInputStream(ze)); int readLen = 0; while ((readLen = inputStream.read(buf, 0, 1024)) != -1) { outputStream.write(buf, 0, readLen); } inputStream.close(); outputStream.close(); } catch (Exception e) { // log.info("解压失败:"+e.toString()); throw new IOException("解压失败:" + e.toString()); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ex) { } } if (outputStream != null) { try { outputStream.close(); } catch (IOException ex) { ex.printStackTrace(); } } inputStream = null; outputStream = null; } } zfile.close(); } /** * * 给定根目录,返回一个相对路径所对应的实际文件名. * * @param zippath * 指定根目录 * * @param absFileName * 相对路径名,来自于ZipEntry中的name * * @return java.io.File 实际的文件 * */ private static File getRealFileName(String zippath, String absFileName) { // log.info("文件名:"+absFileName); String[] dirs = absFileName.split("/", absFileName.length()); File ret = new File(zippath);// 创建文件对象 if (dirs.length > 1) { for (int i = 0; i < dirs.length - 1; i++) { ret = new File(ret, dirs[i]); } } if (!ret.exists()) {// 检测文件是否存在 ret.mkdirs();// 创建此抽象路径名指定的目录 } ret = new File(ret, dirs[dirs.length - 1]);// 根据 ret 抽象路径名和 child // 路径名字符串创建一个新 File 实例 return ret; } }

文件递归删除工具类(file.delete方法必须文件为空才能删除,所以用这个递归方法删)/** * 递归删除目录下的所有文件及子目录下所有文件 * @param dir 将要删除的文件目录 */ private static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i=0; i

判断zip压缩包是否有文件夹思路

/** * 判断是否存在所内所外俩个文件夹 * @param oriName * @param savePath * @return * @throws Exception */ private boolean hasFileDirectory(String oriName, String savePath) throws Exception { ZipFile zfile = new ZipFile(oriName, "gbk");// 连接待解压文件 "utf-8"会乱码 Enumeration zList = zfile.getEntries();// 得到zip包里的所有元素 ZipEntry ze = null; int count = 0; while (zList.hasMoreElements()) { ze = (ZipEntry) zList.nextElement(); if (ze.isDirectory()) { if(ze.getName().equals("所内/")) { count+=1; } if(ze.getName().equals("所外/")) { count+=1; } } // log.info("打开zip文件里的文件夹:"+ ze.getName() +"skipped..."); } if(count==2) { return true; } return false; }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java提供了ZipInputStream和ZipOutputStream两个类来进行zip文件的读取和写入操作,可以不需要解压实现替换zip压缩包里面文件夹中的指定文件。以下是实现的步骤: 1. 创建ZipInputStream对象,读取zip文件中的内容。 2. 创建ZipOutputStream对象,向zip文件中写入内容。 3. 遍历ZipInputStream中的每一个ZipEntry,如果是要替换的文件,则跳过,否则将其写入ZipOutputStream中。 4. 将要替换的文件写入ZipOutputStream中。 5. 关闭ZipInputStream和ZipOutputStream对象。 以下是一个代码示例: ```java import java.io.*; import java.util.zip.*; public class ReplaceFileInZip { public static void main(String[] args) throws IOException { String zipFilePath = "test.zip"; String fileNameToReplace = "test.txt"; String replacementFilePath = "replacement.txt"; // 创建ZipInputStream对象,读取zip文件中的内容 ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath)); // 创建ZipOutputStream对象,向zip文件中写入内容 ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("temp.zip")); // 遍历ZipInputStream中的每一个ZipEntry,如果是要替换的文件,则跳过,否则将其写入ZipOutputStream中 ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { if (entry.getName().equals(fileNameToReplace)) { continue; // 不写入要替换的文件 } zos.putNextEntry(new ZipEntry(entry.getName())); byte[] buffer = new byte[1024]; int len; while ((len = zis.read(buffer)) > 0) { zos.write(buffer, 0, len); } zos.closeEntry(); } // 将要替换的文件写入ZipOutputStream中 ZipEntry replacementEntry = new ZipEntry(fileNameToReplace); zos.putNextEntry(replacementEntry); FileInputStream fis = new FileInputStream(replacementFilePath); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) > 0) { zos.write(buffer, 0, len); } fis.close(); zos.closeEntry(); // 关闭ZipInputStream和ZipOutputStream对象 zis.close(); zos.close(); // 删除原来的zip文件并将新的temp.zip文件重命名为原来的文件名 new File(zipFilePath).delete(); new File("temp.zip").renameTo(new File(zipFilePath)); } } ``` 在上面的示例中,我们将test.zip文件中的test.txt文件替换为replacement.txt文件。注意,这个示例只是演示了如何进行zip文件中指定文件的替换,实际应用中还需要考虑异常处理、路径处理等问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值