Explorar el Código

试玩模块创建和优化2

zhaoxian hace 4 años
padre
commit
0e86ab50b0

+ 7 - 70
module-shiwan/src/main/java/cn/com/ctop/shiwan/modules/FileUtil.java

@@ -21,8 +21,6 @@ import java.util.zip.ZipEntry;
 import java.util.zip.ZipOutputStream;
 
 /**
- * TODO
- *
  * @ClassName ZipUtil
  * @Author ZHAOXA
  * @date 2020-10-23 10:05
@@ -113,45 +111,6 @@ public class FileUtil {
         return realPath;
     }
 
-
-    /**
-     * //创建zip方法,其中的参数ZipFileName是压缩后文件,inputFile要压缩的文件。
-     *
-     * @param
-     * @return void
-     * @throws
-     * @author ZHAOXA
-     */
-    public static void zip(String ZipFileName, File inputFile) throws IOException {
-        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(ZipFileName));//创建了输出流,这里ZipOutputStream()的参数是FileOutPutStream的原因是因为ZIP压缩的对象是文件。
-        zip(out, inputFile, "");//调用zip方法,实现了zip的重载。这次的参数是本方法中定义过的输出流out,要压缩的文件:inputFile以及文件最后的存储目录base
-        log.info("压缩中....");
-        out.close();
-        log.info("压缩完成!");
-    }
-
-    public static void zip(ZipOutputStream out, File f, String base) throws IOException {//方法重载
-        if (f.isDirectory()) {//判断要压缩的文件是否是文件夹
-            File[] fl = f.listFiles();//如果是文件夹就对把该文件夹中的文件的路径以文件数组的形式获得
-            if (base.length() != 0) {//判断最后要存储的路径是否已存在
-                out.putNextEntry(new ZipEntry(base + "/"));//如果已经存在,写入此目录的entry
-            }
-            for (int i = 0; i < fl.length; i++) {//遍历文件数组
-                zip(out, fl[i], base + fl[i]);//将文件数组中的文件添加到已经创建的ZIP中。
-            }
-        } else {
-            out.putNextEntry(new ZipEntry(base));//如果base为空。那么就创建新的进入点
-            //创建FileInputStream对象
-            FileInputStream in = new FileInputStream(f);//创建该输入流的原因是为了后边判断该流是否到达尾部
-            int b;
-            System.out.println(base);
-            while ((b = in.read()) != -1) {
-                out.write(b);//在没有到达尾部的情况下向已经创建的ZIP中添加
-            }
-            in.close();//关闭流
-        }
-    }
-
     /**
      * 文件压缩方法
      *
@@ -207,17 +166,6 @@ public class FileUtil {
         } catch (Exception e) {
             log.error("[ ==========压缩文件异常 ========== ]", e);
             return null;
-        } finally {
-            try {
-                if (is != null) {
-                    is.close();
-                }
-                if (zos != null) {
-                    zos.close();
-                }
-            } catch (IOException e) {
-                log.error("[ ==========关闭IO流失败========== ]", e);
-            }
         }
         long end = System.currentTimeMillis();
         log.info("文件压缩完成,耗时:{} ms", (end - start));
@@ -234,18 +182,11 @@ public class FileUtil {
      * @author ZHAOXA
      */
     public static String approvalFile(MultipartFile filecontent, String path) {
+        InputStream is = null;
         OutputStream os = null;
-        InputStream inputStream = null;
         String fileName = filecontent.getOriginalFilename();
         try {
-            inputStream = filecontent.getInputStream();
-        } catch (IOException e) {
-            log.error("获取文件流异常");
-        }
-        try {
-            byte[] bs = new byte[1024];
-            // 读取到的数据长度
-            int len;
+            is = filecontent.getInputStream();
             // 输出的文件流保存到本地文件
             File tempFile = new File(path);
             if (!tempFile.exists()) {
@@ -253,19 +194,15 @@ public class FileUtil {
             }
             os = new FileOutputStream(tempFile.getPath() + "/" + File.separator + fileName);
             // 开始读取
-            while ((len = inputStream.read(bs)) != -1) {
+            int len;
+            byte[] bs = new byte[1024];
+            while ((len = is.read(bs)) != -1) {
                 os.write(bs, 0, len);
             }
+            os.close();
+            is.close();
         } catch (Exception e) {
             log.error("获取文件的本地路径失败", e);
-        } finally {
-            // 完毕,关闭所有链接
-            try {
-                os.close();
-                inputStream.close();
-            } catch (IOException e) {
-                e.printStackTrace();
-            }
         }
         return path + fileName;
     }

+ 39 - 8
module-shiwan/src/main/java/cn/com/ctop/shiwan/modules/service/ShiwanFileUploadServiceImpl.java

@@ -54,7 +54,7 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
         ShiwanFileUpload existFiles = getExistFiles(userId, accountId, file.getOriginalFilename(), fileType, parentId);
         StringBuffer path = new StringBuffer();
         path.append(downloadPath).append(DateUtils.getNowDate(DateUtils.WEB_FORMAT)).append("/").append(UUID.randomUUID().toString()).append("/");
-        log.info("----------下载到服务器地址:{}", path.toString());
+        log.info("-------下载到服务器地址:{}", path.toString());
         ShiwanFileUpload shiwanFileUpload = null;
         String newFileUrl = FileUtil.approvalFile(file, path.toString());
         String md5 = null;
@@ -64,24 +64,38 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
             log.error("获取MD5签名失败", e);
         }
         if (!Check.isNull(existFiles)) {
+            long start = System.currentTimeMillis();
             existFiles.setSignature(md5);
-            shiwanFileUpload = updateFile(file, existFiles);
+            try {
+                shiwanFileUpload = updateFile(file, existFiles);
+            } catch (IOException e) {
+                log.error("更新文件,上传SOC异常", e);
+            }
             if (!Check.isNull(shiwanFileUpload)) {
                 List<String> urlList = unzipFiles(shiwanFileUpload, path.toString(), newFileUrl);
                 saveInnerFiles(shiwanFileUpload, urlList);
             }
+            long end = System.currentTimeMillis();
+            log.info("文件更新完成,耗时:{} ms", (end - start));
         } else {
+            long start = System.currentTimeMillis();
             ShiwanFileUpload fileUpload = new ShiwanFileUpload();
             fileUpload.setSignature(md5);
             fileUpload.setUserId(userId);
             fileUpload.setAccountId(accountId);
             fileUpload.setFileType(fileType);
             fileUpload.setParentId(parentId);
-            shiwanFileUpload = saveFile(file, fileUpload, uuid);
+            try {
+                shiwanFileUpload = saveFile(file, fileUpload, uuid);
+            } catch (IOException e) {
+                log.error("新增文件,上传SOC异常", e);
+            }
             if (!Check.isNull(shiwanFileUpload)) {
                 List<String> urlList = unzipFiles(shiwanFileUpload, path.toString(), newFileUrl);
                 saveInnerFiles(shiwanFileUpload, urlList);
             }
+            long end = System.currentTimeMillis();
+            log.info("文件新增完成,耗时:{} ms", (end - start));
         }
         return shiwanFileUpload;
     }
@@ -94,7 +108,7 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
      * @throws
      * @author ZHAOXA
      */
-    private ShiwanFileUpload updateFile(MultipartFile file, ShiwanFileUpload existFiles) {
+    private ShiwanFileUpload updateFile(MultipartFile file, ShiwanFileUpload existFiles) throws IOException {
         ResFileDTO resultFile = null;
         String url = "";
         ShiwanFileUpload fileUpload = new ShiwanFileUpload();
@@ -103,10 +117,15 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
         } else {
             url = "try-play/zip/";
         }
+        InputStream inputStream = null;
         try {
-            resultFile = CosUtils.uploadDetailInputStreamV2(file.getInputStream(), existFiles.getCfileName(), existFiles.getFileSuffix(), file.getSize(), url);
+            inputStream = file.getInputStream();
+            resultFile = CosUtils.uploadDetailInputStreamV2(inputStream, existFiles.getCfileName(), existFiles.getFileSuffix(), file.getSize(), url);
+            inputStream.close();
         } catch (IOException e) {
             log.error("更新文件,上传COS失败", e);
+        } finally {
+            inputStream.close();
         }
         QueryWrapper<ShiwanFileUpload> queryWrapper = new QueryWrapper<>();
         queryWrapper.eq("id", existFiles.getId());
@@ -125,7 +144,7 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
      * @throws
      * @author ZHAOXA
      */
-    private ShiwanFileUpload saveFile(MultipartFile file, ShiwanFileUpload fileUpload, String uuid) {
+    private ShiwanFileUpload saveFile(MultipartFile file, ShiwanFileUpload fileUpload, String uuid) throws IOException {
         String filename = file.getOriginalFilename();
         ResFileDTO resultFile = null;
         String url = "";
@@ -136,10 +155,15 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
             url = "try-play/inner-file/".concat(uuid).concat("/");
         }
         String fileSuffix = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
+        InputStream inputStream = null;
         try {
-            resultFile = CosUtils.uploadDetailInputStream(file.getInputStream(), filename, fileSuffix, file.getSize(), url);
+            inputStream = file.getInputStream();
+            resultFile = CosUtils.uploadDetailInputStream(inputStream, filename, fileSuffix, file.getSize(), url);
+            inputStream.close();
         } catch (IOException e) {
             log.error("上传COS异常", e);
+        } finally {
+            inputStream.close();
         }
         if (!Check.isNull(resultFile)) {
             fileUpload.setCfileName(resultFile.getCFileName());
@@ -206,6 +230,7 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
      * @author ZHAOXA
      */
     private List<String> unzipFiles(ShiwanFileUpload fileUpload, String path, String innerZipPath) {
+        long start = System.currentTimeMillis();
         List<String> urlList = new ArrayList<>();
         //下载到本地服务器
         if (Check.isNull(innerZipPath)) {
@@ -251,6 +276,8 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
             log.error("解压原zip文件失败 ", e);
         }
         deletelocalFiles(innerZipPath);
+        long end = System.currentTimeMillis();
+        log.info("文件解压完成,耗时:{} ms", (end - start));
         return urlList;
     }
 
@@ -304,7 +331,11 @@ public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMap
                 log.error("获取MD5签名失败", e);
             }
             mulFileByPath = FileUtil.getMulFileByPath(url);
-            saveFile(mulFileByPath, shiwanFileUpload, newZipEntity.getCfileName());
+            try {
+                saveFile(mulFileByPath, shiwanFileUpload, newZipEntity.getCfileName());
+            } catch (IOException e) {
+                log.error("新增内部文件,上传SOC异常", e);
+            }
             deletelocalFiles(url);
         }
     }