Selaa lähdekoodia

解压zip包方法从hutool替换为commons.compress

小王 1 vuosi sitten
vanhempi
commit
2261cc8016

+ 34 - 17
src/main/java/com/example/bigsql/service/CreateDatabasesByV3File.java

@@ -4,15 +4,14 @@ package com.example.bigsql.service;
 import cn.hutool.core.date.DatePattern;
 import cn.hutool.core.date.DateUtil;
 import cn.hutool.core.io.FileUtil;
-import cn.hutool.core.util.ZipUtil;
 import com.example.bigsql.entity.UploadBigsqlFileRecordBaseVO;
 import com.example.bigsql.util.ExecuteShellUtil;
 import com.example.bigsql.util.JyDbUtil;
+import com.example.bigsql.util.UnZipUtil;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Service;
 
 import java.io.*;
-import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Paths;
 import java.sql.*;
@@ -199,6 +198,7 @@ public class CreateDatabasesByV3File {
      * 读取文件 并创建数据库和表
      */
     public void redSqlZip() throws Exception {
+        boolean flag = false;
         //未解析的sql压缩包包
         List<UploadBigsqlFileRecordBaseVO> list = queryRecords();
         log.info("找到" + list.size() + "条待恢复记录");
@@ -229,7 +229,7 @@ public class CreateDatabasesByV3File {
                 //获取文件输入流
                 BufferedInputStream input = new BufferedInputStream(Files.newInputStream(Paths.get(f.getPath())));
                 //扫描解压目录下的sql文件 正常没有数据或只有一条数据
-                ZipUtil.unzip(f.getPath(), sqlPath, StandardCharsets.UTF_8);
+                UnZipUtil.decompressZip(f.getPath(), sqlPath);
                 File sFile = new File(sqlPath);
                 File[] sFiles = searchFile(sFile, ".sql");
                 if (sFiles.length == 0) {
@@ -263,35 +263,52 @@ public class CreateDatabasesByV3File {
                         sqlStatements = sqlStatements.stream().filter(s -> s.startsWith("CREATE") || s.startsWith("DROP")).collect(Collectors.toList());
                         databasesName = "ipfcst_" + name + "_" + DateUtil.format(new Date(), DatePattern.PURE_DATETIME_FORMAT);
                         Connection conn = JyDbUtil.conn;
-                        if (createDatabase(databasesName, conn)) {
-                            if (createTable(databasesName, sqlStatements, conn)) {
-                                log.info("执行数据库和数据表创建成功,其中数据共:" + lineSize);
+
+                        int num = 0;
+                        while (!flag) {
+                            if (createDatabase(databasesName, conn)) {
+                                if (createTable(databasesName, sqlStatements, conn)) {
+                                    flag = true;
+                                }
+                                num++;
+                            }
+                            if (num == 2) {
+                                break;
                             }
                         }
+                        if (flag) {
+                            log.info("执行数据库和数据表创建成功,其中数据共:" + lineSize);
+                        } else {
+                            log.info("执行数据库和数据表创建失败");
+                        }
                     } catch (IOException e) {
                         updateRecords(list.get(0).getId(), "2", databasesName);
                         throw new RuntimeException("读取Sql文件失败:  " + f.getName(), e);
                     }
                     input.close();
                     //修改cloud数据库表里的状态
-                    updateRecords(list.get(0).getId(), "1", databasesName);
+                    if (flag) {
+                        updateRecords(list.get(0).getId(), "1", databasesName);
+                    }
                 } catch (Exception e) {
                     log.info("读取zip文件时异常" + e);
                 } finally {
                     input.close();
                 }
-                log.info("表结构导入完毕,开始进行表数据导入");
-                File csvFile = new File(csvFilePath);
-                File[] csvFiles = csvFile.listFiles();
-                if (csvFiles != null) {
-                    for (File csv : csvFiles) {
-                        insertData(databasesName, csv);
+                if (flag) {
+                    log.info("表结构导入完毕,开始进行表数据导入");
+                    File csvFile = new File(csvFilePath);
+                    File[] csvFiles = csvFile.listFiles();
+                    if (csvFiles != null) {
+                        for (File csv : csvFiles) {
+                            insertData(databasesName, csv);
+                        }
                     }
+                    log.info("数据导入完毕!!!");
+                    FileUtil.del(sqlPath);
+                    FileUtil.del(csvFilePath);
+                    FileUtil.move(f, new File(path + File.separator + "backUps" + DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN) + File.separator + f.getName()), true);
                 }
-                log.info("数据导入完毕!!!");
-                FileUtil.del(sqlPath);
-                FileUtil.del(csvFilePath);
-                FileUtil.move(f, new File(path + File.separator + "backUps" + DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN) + File.separator + f.getName()), true);
             }
         }
     }

+ 66 - 83
src/main/java/com/example/bigsql/util/UnZipUtil.java

@@ -2,110 +2,93 @@ package com.example.bigsql.util;
 
 import com.github.junrar.Archive;
 import com.github.junrar.rarfile.FileHeader;
+import org.apache.commons.compress.archivers.ArchiveEntry;
+import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
 
 import java.io.*;
-import java.nio.charset.Charset;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.PreparedStatement;
 import java.sql.SQLException;
-import java.util.Enumeration;
 import java.util.zip.GZIPInputStream;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipFile;
-import java.util.zip.ZipInputStream;
 
 public class UnZipUtil {
     //解压.zip文件
-    public static void unZip(String sourceFile, String outputDir) throws IOException {
-        ZipFile zipFile = null;
-        File file = new File(sourceFile);
-        try {
-            Charset CP866 = StandardCharsets.UTF_8;  //specifying alternative (non UTF-8) charset
-            zipFile = new ZipFile(file, Charset.forName("GBK"));
-            createDirectory(outputDir, null);//创建输出目录
-
-            Enumeration<?> enums = zipFile.entries();
-            while (enums.hasMoreElements()) {
-
-                ZipEntry entry = (ZipEntry) enums.nextElement();
-                System.out.println("解压." + entry.getName());
 
-                if (entry.isDirectory()) {//是目录
-                    createDirectory(outputDir, entry.getName());//创建空目录
-                } else {//是文件
-                    File tmpFile = new File(outputDir + "/" + entry.getName());
-                    createDirectory(tmpFile.getParent() + "/", null);//创建输出目录
-
-                    try (InputStream in = zipFile.getInputStream(entry); OutputStream out = Files.newOutputStream(tmpFile.toPath())) {
-                        int length = 0;
-
-                        byte[] b = new byte[2048];
-                        while ((length = in.read(b)) != -1) {
-                            out.write(b, 0, length);
+    /**
+     * 把zip文件解压到指定的文件夹
+     *
+     * @param zipFilePath zip文件路径, 如 "D:/test/aa.zip"
+     * @param saveFileDir 解压后的文件存放路径, 如"D:/test/"
+     */
+    public static void decompressZip(String zipFilePath, String saveFileDir) {
+        if (isEndsWithZip(zipFilePath)) {
+            File file = new File(zipFilePath);
+            if (file.exists()) {
+                InputStream is = null;
+                //can read Zip archives
+                ZipArchiveInputStream zais = null;
+                try {
+                    is = new FileInputStream(file);
+                    zais = new ZipArchiveInputStream(is);
+                    ArchiveEntry archiveEntry = null;
+                    //把zip包中的每个文件读取出来
+                    //然后把文件写到指定的文件夹
+                    while ((archiveEntry = zais.getNextEntry()) != null) {
+                        //获取文件名
+                        String entryFileName = archiveEntry.getName();
+                        //构造解压出来的文件存放路径
+                        String entryFilePath = saveFileDir + entryFileName;
+                        byte[] content = new byte[(int) archiveEntry.getSize()];
+                        zais.read(content);
+                        OutputStream os = null;
+                        try {
+                            //把解压出来的文件写到指定路径
+                            File entryFile = new File(entryFilePath);
+                            os = new BufferedOutputStream(new FileOutputStream(entryFile));
+                            os.write(content);
+                        } catch (IOException e) {
+                            throw new IOException(e);
+                        } finally {
+                            if (os != null) {
+                                os.flush();
+                                os.close();
+                            }
                         }
 
                     }
+                } catch (Exception e) {
+                    throw new RuntimeException(e);
+                } finally {
+                    try {
+                        if (zais != null) {
+                            zais.close();
+                        }
+                        if (is != null) {
+                            is.close();
+                        }
+                    } catch (IOException e) {
+                        throw new RuntimeException(e);
+                    }
                 }
             }
-
-        } catch (IOException e) {
-            throw new IOException("解压缩文件出现异常", e);
-        } finally {
-            try {
-                if (zipFile != null) {
-                    zipFile.close();
-                }
-            } catch (IOException ex) {
-                throw new IOException("关闭zipFile出现异常", ex);
-            }
         }
     }
 
-    public static void unzip1(File file, String outputDir) throws IOException {
-        File outFile = null;   // 输出文件的时候要有文件夹的操作
-        ZipFile zipFile = new ZipFile(file.getPath());   // 实例化ZipFile对象
-        ZipInputStream zipInput = null;    // 定义压缩输入流
-
-        //定义解压的文件名
-        OutputStream out = null;   // 定义输出流,用于输出每一个实体内容
-        InputStream input = null;  // 定义输入流,读取每一个ZipEntry
-        ZipEntry entry = null; // 每一个压缩实体
-        zipInput = new ZipInputStream(new FileInputStream(file));  // 实例化ZIpInputStream
-
-        //遍历压缩包中的文件
-        while ((entry = zipInput.getNextEntry()) != null) { // 得到一个压缩实体
-            System.out.println("解压缩" + entry.getName() + "文件");
-            outFile = new File(outputDir + File.separator + entry.getName());   // 定义输出的文件路径
-            if (!outFile.getParentFile().exists()) {  // 如果输出文件夹不存在
-                outFile.getParentFile().mkdirs();
-                // 创建文件夹 ,如果这里的有多级文件夹不存在,请使用mkdirs()
-                // 如果只是单纯的一级文件夹,使用mkdir()就好了
-            }
-            if (!outFile.exists()) {  // 判断输出文件是否存在
-                if (entry.isDirectory()) {
-                    outFile.mkdirs();
-                    System.out.println("create directory...");
-                } else {
-                    outFile.createNewFile();   // 创建文件
-                    System.out.println("create file...");
-                }
-            }
-            if (!entry.isDirectory()) {
-                input = zipFile.getInputStream(entry); // 得到每一个实体的输入流
-                out = new FileOutputStream(outFile);   // 实例化文件输出流
-                int temp = 0;
-                while ((temp = input.read()) != -1) {
-                    out.write(temp);
-                }
-                input.close();     // 关闭输入流
-                out.close();   // 关闭输出流
+    /**
+     * 判断文件名是否以.zip为后缀
+     *
+     * @param fileName 需要判断的文件名
+     * @return 是zip文件返回true, 否则返回false
+     */
+    public static boolean isEndsWithZip(String fileName) {
+        boolean flag = false;
+        if (fileName != null && !"".equals(fileName.trim())) {
+            if (fileName.endsWith(".ZIP") || fileName.endsWith(".zip")) {
+                flag = true;
             }
-
         }
-        input.close();
+        return flag;
     }
 
     /**