Browse Source

试玩模块创建和优化

zhaoxian 4 years ago
parent
commit
884860aa65

+ 65 - 20
module-shiwan/src/main/java/cn/com/ctop/shiwan/modules/FileUtil.java

@@ -96,7 +96,7 @@ public class FileUtil {
                     return null;
                 }
             }
-            realPath = locationPath.concat("/").concat(fileName);
+            realPath = locationPath.concat(fileName);
             os = new FileOutputStream(realPath);
             int bytesRead = 0;
             byte[] buffer = new byte[8192];
@@ -104,24 +104,11 @@ public class FileUtil {
                 os.write(buffer, 0, bytesRead);
                 os.flush();
             }
+            os.close();
+            is.close();
         } catch (Exception e) {
             log.error(" ========== 文件下载到本地异常:", e);
             return null;
-        } finally {
-            try {
-                if (os != null) {
-                    os.close();
-                }
-            } catch (IOException e) {
-                log.error("Close OutputStream error", e);
-            }
-            try {
-                if (is != null) {
-                    is.close();
-                }
-            } catch (IOException e) {
-                log.error("Close InputStream error", e);
-            }
         }
         return realPath;
     }
@@ -177,6 +164,7 @@ public class FileUtil {
      * @date 2020年1月20日
      */
     public static String listToZip(List<String> list, String localPath, String zipfilename) {
+        long start = System.currentTimeMillis();
         FileInputStream is = null;
         ZipOutputStream zos = null;
         String realPath = localPath + "/newFiles/" + zipfilename;
@@ -210,10 +198,6 @@ public class FileUtil {
                         }
                         zos.closeEntry();
                         is.close();
-                      /*  if (file.delete()) {
-                            // 删除图片
-                            log.debug("[ ===== File deleted successfully ===== ]");
-                        }*/
                     } else {
                         log.warn("[ ======= {} 源文件不存在 ======= ]", path);
                         return null;
@@ -235,6 +219,8 @@ public class FileUtil {
                 log.error("[ ==========关闭IO流失败========== ]", e);
             }
         }
+        long end = System.currentTimeMillis();
+        log.info("文件压缩完成,耗时:{} ms", (end - start));
         return realPath;
     }
 
@@ -284,4 +270,63 @@ public class FileUtil {
         return path + fileName;
     }
 
+
+    /**
+     * @param zipSavePath 压缩好的zip包存放路径
+     * @param sourceFile  待压缩的文件(单个文件或者整个文件目录)
+     * @return
+     * @Description
+     * @author xukaixun
+     */
+    public static String zipCompress(String zipPath, File sourceFile) {
+        try {
+            //创建zip输出流
+            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipPath));
+            File[] fileList = sourceFile.listFiles();
+            if (fileList.length != 0) {
+                for (File file : fileList) {
+                    //根据filename判断是否要最外层文件夹
+                    compress(zos, file, file.getName());
+                }
+                zos.close();
+            }
+        } catch (Exception e) {
+            log.error("压缩文件异常: {}, zipSavePath={}, sourceFile={}", e, zipPath, sourceFile.getName());
+        }
+        return zipPath;
+    }
+
+    private static void compress(ZipOutputStream zos, File sourceFile, String fileName) throws Exception {
+        if (sourceFile.isDirectory()) {
+            //如果是文件夹,取出文件夹中的文件(或子文件夹)
+            File[] fileList = sourceFile.listFiles();
+            if (fileList.length == 0)//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入点
+            {
+                zos.putNextEntry(new ZipEntry(fileName + "/"));
+            } else//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩
+            {
+                for (File file : fileList) {
+                    compress(zos, file, fileName + "/" + file.getName());
+                }
+            }
+        } else {
+            if (!sourceFile.exists()) {
+                zos.putNextEntry(new ZipEntry("/"));
+                zos.closeEntry();
+            } else {
+                //单个文件,直接将其压缩到zip包中
+                zos.putNextEntry(new ZipEntry(fileName));
+                FileInputStream fis = new FileInputStream(sourceFile);
+                byte[] buf = new byte[1024];
+                int len;
+                //将源文件写入到zip文件中
+                while ((len = fis.read(buf)) != -1) {
+                    zos.write(buf, 0, len);
+                }
+                zos.closeEntry();
+                fis.close();
+            }
+        }
+    }
+
 }

+ 28 - 23
module-shiwan/src/main/java/cn/com/ctop/shiwan/modules/service/ShiwanFileUploadServiceImpl.java

@@ -53,14 +53,13 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
     public ShiwanFileUpload saveOrUpdateFile(MultipartFile file, String userId, Long accountId, String fileType, Long parentId, String uuid) {
         ShiwanFileUpload existFiles = getExistFiles(userId, accountId, file.getOriginalFilename(), fileType, parentId);
         StringBuffer path = new StringBuffer();
-        String uuids = UUID.randomUUID().toString();
-        path.append(downloadPath).append(DateUtils.getNowDate(DateUtils.WEB_FORMAT)).append("/").append(uuids).append("/");
-        log.info("----------服务器下载地址:{}", path.toString());
+        path.append(downloadPath).append(DateUtils.getNowDate(DateUtils.WEB_FORMAT)).append("/").append(UUID.randomUUID().toString()).append("/");
+        log.info("----------下载到服务器地址:{}", path.toString());
         ShiwanFileUpload shiwanFileUpload = null;
-        String newUrl = FileUtil.approvalFile(file, path.toString());
+        String newFileUrl = FileUtil.approvalFile(file, path.toString());
         String md5 = null;
         try {
-            md5 = LoadFileUtil.getMD5(newUrl);
+            md5 = LoadFileUtil.getMD5(newFileUrl);
         } catch (IOException e) {
             log.error("获取MD5签名失败", e);
         }
@@ -68,7 +67,7 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
             existFiles.setSignature(md5);
             shiwanFileUpload = updateFile(file, existFiles);
             if (!Check.isNull(shiwanFileUpload)) {
-                List<String> urlList = unzipFiles(shiwanFileUpload, path.toString());
+                List<String> urlList = unzipFiles(shiwanFileUpload, path.toString(), newFileUrl);
                 saveInnerFiles(shiwanFileUpload, urlList);
             }
         } else {
@@ -80,7 +79,7 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
             fileUpload.setParentId(parentId);
             shiwanFileUpload = saveFile(file, fileUpload, uuid);
             if (!Check.isNull(shiwanFileUpload)) {
-                List<String> urlList = unzipFiles(shiwanFileUpload, path.toString());
+                List<String> urlList = unzipFiles(shiwanFileUpload, path.toString(), newFileUrl);
                 saveInnerFiles(shiwanFileUpload, urlList);
             }
         }
@@ -169,23 +168,27 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
         path.append(downloadPath).append(DateUtils.getNowDate(DateUtils.WEB_FORMAT)).append("/").append(uuid).append("/");
         log.info("----------服务器下载地址:{}", path.toString());
         //解压zip文件
-        List<String> urlList = unzipFiles(fileUpload, path.toString());
+        List<String> urlList = unzipFiles(fileUpload, path.toString(), null);
+        String newFilePath = "";
         if (null != urlList && urlList.size() > 0) {
             Iterator it = urlList.iterator();
             while (it.hasNext()) {
                 String url = it.next().toString();
                 String fileName = url.substring(url.lastIndexOf("/") + 1);
                 if (updateName.equals(fileName)) {
+                    newFilePath = url.substring(0, url.lastIndexOf("/") + 1);
                     //移除被替换的对象
                     it.remove();
+                    deletelocalFiles(url);
+                    break;
                 }
             }
         }
         //添加上新的对象
-        String newUrl = FileUtil.approvalFile(file, path.toString());
+        String newUrl = FileUtil.approvalFile(file, newFilePath);
         urlList.add(newUrl);
         //压缩zip文件
-        String newFileName = DateUtils.getNowDate(DateUtils.LONG_FORMAT).concat("_COPYFROM_").concat(fileUpload.getFileName());
+        String newFileName = DateUtils.getNowDate(DateUtils.LONG_FORMAT).concat("_COPY-FROM_").concat(fileUpload.getFileName());
         return createNewZipFiles(urlList, path.toString(), newFileName, updateName, userId, accountId, fileType);
     }
 
@@ -202,25 +205,27 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
      * @throws
      * @author ZHAOXA
      */
-    private List<String> unzipFiles(ShiwanFileUpload fileUpload, String path) {
+    private List<String> unzipFiles(ShiwanFileUpload fileUpload, String path, String innerZipPath) {
         List<String> urlList = new ArrayList<>();
+        //下载到本地服务器
+        if (Check.isNull(innerZipPath)) {
+            innerZipPath = FileUtil.writeFiles(path.concat("oldZip/"), fileUpload.getFileUrl(), fileUpload.getCfileName());
+        }
         try {
-            //下载到本地服务器
-            String innerZipPath = FileUtil.writeFiles(path.concat("oldZip/"), fileUpload.getFileUrl(), fileUpload.getCfileName());
-            log.info("----------zip包解压地址:{}", innerZipPath);
+            log.info("----------zip包下载地址:{}", innerZipPath);
             ZipFile zipFile = new ZipFile(innerZipPath, Charset.forName("GBK"));
             Enumeration<?> enumeration = zipFile.entries();
             ZipEntry zipEntry = null;
-            path.concat("innerFile/");
+            String innerPath = path.concat("innerFiles/");
             while (enumeration.hasMoreElements()) {
                 zipEntry = (ZipEntry) enumeration.nextElement();
                 // 如果是文件夹,就创建个文件夹
                 if (zipEntry.isDirectory()) {
-                    String dirPath = path + zipEntry.getName();
+                    String dirPath = innerPath + zipEntry.getName();
                     File dir = new File(dirPath);
                     dir.mkdirs();
                 } else {
-                    String url = path + zipEntry.getName();
+                    String url = innerPath + zipEntry.getName();
                     // 如果是文件,就先创建一个文件,然后用io流把内容copy过去
                     File targetFile = new File(url);
                     // 保证这个文件的父文件夹必须要存在
@@ -232,20 +237,20 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
                     InputStream is = zipFile.getInputStream(zipEntry);
                     FileOutputStream fos = new FileOutputStream(targetFile);
                     int len;
-                    byte[] buf = new byte[8192];
+                    byte[] buf = new byte[2048];
                     while ((len = is.read(buf)) != -1) {
                         fos.write(buf, 0, len);
                     }
-                    urlList.add(url);
                     // 关流顺序,先打开的后关闭
                     fos.close();
                     is.close();
+                    urlList.add(url);
                 }
             }
-            deletelocalFiles(path.concat("oldZip/").concat(fileUpload.getCfileName()));
         } catch (IOException e) {
-            log.error("解压原zip失败 ", e);
+            log.error("解压原zip文件失败 ", e);
         }
+        deletelocalFiles(innerZipPath);
         return urlList;
     }
 
@@ -257,8 +262,8 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
      * @throws
      * @author ZHAOXA
      */
-    private ShiwanFileUpload createNewZipFiles(List<String> list, String innerFilePath, String zipfilename, String updateName, String userId, Long accountId, String fileType) throws IOException {
-        String zipUrl = FileUtil.listToZip(list, innerFilePath, zipfilename);
+    private ShiwanFileUpload createNewZipFiles(List<String> list, String path, String zipfilename, String updateName, String userId, Long accountId, String fileType) throws IOException {
+        String zipUrl = FileUtil.zipCompress(path.concat(zipfilename), new File(path.concat("innerFiles/")));
         ShiwanFileUpload shiwanFileUpload = new ShiwanFileUpload();
         shiwanFileUpload.setUserId(userId);
         shiwanFileUpload.setAccountId(accountId);