Forráskód Böngészése

Use try-with-resources close io streams

deason 5 éve
szülő
commit
1bb13f1af6

+ 84 - 102
examcloud-core-questions-base/src/main/java/cn/com/qmth/examcloud/core/questions/base/FileDisposeUtil.java

@@ -1,13 +1,13 @@
 package cn.com.qmth.examcloud.core.questions.base;
 
 import org.apache.commons.io.FileUtils;
-import org.apache.commons.io.IOUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import javax.servlet.http.HttpServletResponse;
 import java.io.*;
 import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
 import java.net.URL;
 import java.net.URLEncoder;
 import java.nio.file.Files;
@@ -23,7 +23,6 @@ import java.util.zip.ZipOutputStream;
  * @company QMTH
  */
 public class FileDisposeUtil {
-
     private static final Logger logger = LoggerFactory.getLogger(FileDisposeUtil.class);
 
     /**
@@ -34,40 +33,39 @@ public class FileDisposeUtil {
      * @return
      */
     public static boolean saveUrlAs(String fileUrl, String localFilePath) {
-        HttpURLConnection connection = null;
-        FileOutputStream fileOutputStream = null;
-        DataOutputStream dataOutputStream = null;
-        DataInputStream dataInputStream = null;
+        URL url;
+        try {
+            url = new URL(fileUrl);
+        } catch (MalformedURLException e) {
+            logger.error(e.getMessage(), e);
+            return false;
+        }
+
+        HttpURLConnection connection;
         try {
-            URL url = new URL(fileUrl);
             connection = (HttpURLConnection) url.openConnection();
-            dataInputStream = new DataInputStream(connection.getInputStream());
-            fileOutputStream = new FileOutputStream(localFilePath);
-            dataOutputStream = new DataOutputStream(fileOutputStream);
+        } catch (IOException e) {
+            logger.error(e.getMessage(), e);
+            return false;
+        }
+
+        try (
+                DataInputStream dataInputStream = new DataInputStream(connection.getInputStream());
+                FileOutputStream fileOutputStream = new FileOutputStream(localFilePath);
+                DataOutputStream dataOutputStream = new DataOutputStream(fileOutputStream);
+        ) {
+
             byte[] buffer = new byte[4096];
-            int count = 0;
+            int count;
             while ((count = dataInputStream.read(buffer)) > 0) {
                 dataOutputStream.write(buffer, 0, count);
             }
+            fileOutputStream.flush();
+            dataOutputStream.flush();
             return true;
         } catch (Exception e) {
             return false;
         } finally {
-            try {
-                if (fileOutputStream != null) {
-                    fileOutputStream.flush();
-                    fileOutputStream.close();
-                }
-                if (dataOutputStream != null) {
-                    dataOutputStream.flush();
-                    dataOutputStream.close();
-                }
-                if (dataInputStream != null) {
-                    dataInputStream.close();
-                }
-            } catch (IOException e) {
-                logger.error(e.getMessage(), e);
-            }
             if (connection != null) {
                 connection.disconnect();
             }
@@ -82,10 +80,9 @@ public class FileDisposeUtil {
      * @param response
      */
     public static void downloadFile(String filename, String fullFilePath, HttpServletResponse response) {
-        InputStream in = null;
-        OutputStream out = null;
+        try (InputStream in = new FileInputStream(fullFilePath);
+             OutputStream out = response.getOutputStream();) {
 
-        try {
             //设置编码
             response.setCharacterEncoding("UTF-8");
 
@@ -101,33 +98,17 @@ public class FileDisposeUtil {
             response.setContentType("application/octet-stream;charset=utf-8");
 
             //读取目标文件,通过response将目标文件写到客户端
-            in = new FileInputStream(fullFilePath);
-            out = response.getOutputStream();
-
-            //写文件
             byte[] buffer = new byte[4096];
-            int count = 0;
+            int count;
             while ((count = in.read(buffer)) > 0) {
                 out.write(buffer, 0, count);
             }
+
             response.flushBuffer();
-            out.close();
-            in.close();
         } catch (FileNotFoundException e) {
             logger.error(e.getMessage(), e);
         } catch (IOException e) {
             logger.error(e.getMessage(), e);
-        } finally {
-            try {
-                if (null != out) {
-                    out.close();
-                }
-                if (null != in) {
-                    in.close();
-                }
-            } catch (IOException e) {
-                logger.error(e.getMessage(), e);
-            }
         }
     }
 
@@ -158,67 +139,68 @@ public class FileDisposeUtil {
      */
     public static boolean fileToZip(String sourceFilePath, String zipFilePath, String fileName) {
         logger.info("压缩" + sourceFilePath + "目录开始");
-        boolean flag = false;
+
         File sourceFile = new File(sourceFilePath);
-        FileInputStream fis = null;
-        BufferedInputStream bis = null;
-        FileOutputStream fos = null;
-        ZipOutputStream zos = null;
-        if (sourceFile.exists() == false) {
+        if (!sourceFile.exists()) {
             logger.error("待压缩的文件目录:" + sourceFilePath + "不存在.");
-        } else {
-            try {
-                File zipFile = new File(zipFilePath + File.separator + fileName + ".zip");
-                if (zipFile.exists()) {
-                    logger.error(zipFilePath + "目录下存在名字为:" + fileName + ".zip" + "打包文件.");
-                } else {
-                    File[] sourceFiles = sourceFile.listFiles();
-                    if (null == sourceFiles || sourceFiles.length < 1) {
-                        logger.error("待压缩的文件目录:" + sourceFilePath + "里面不存在文件,无需压缩.");
-                    } else {
-                        fos = new FileOutputStream(zipFile);
-                        zos = new ZipOutputStream(new BufferedOutputStream(fos));
-                        byte[] bufs = new byte[1024 * 10];
-                        for (int i = 0; i < sourceFiles.length; i++) {
-                            File file = sourceFiles[i];
-                            if (!file.isFile()) {
-                                continue;
-                            }
-                            try {
-                                //创建ZIP实体,并添加进压缩包
-                                String fileEncode = System.getProperty("file.encoding");
-                                String name = new String(file.getName().getBytes(fileEncode), "UTF-8");
-                                ZipEntry zipEntry = new ZipEntry(name);
-                                zos.putNextEntry(zipEntry);
-                                //读取待压缩的文件并写进压缩包里
-                                fis = new FileInputStream(file);
-                                bis = new BufferedInputStream(fis, 1024 * 10);
-                                int read = 0;
-                                while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
-                                    zos.write(bufs, 0, read);
-                                }
-                                zos.flush();
-                            } catch (Exception e) {
-                                logger.error(e.getMessage(), e);
-                            } finally {
-                                IOUtils.closeQuietly(bis);
-                                IOUtils.closeQuietly(fis);
-                            }
-                        }
-                        flag = true;
+            return false;
+        }
+
+        File zipFile = new File(zipFilePath + File.separator + fileName + ".zip");
+        if (zipFile.exists()) {
+            logger.error(zipFilePath + "目录下存在名字为:" + fileName + ".zip" + "打包文件.");
+            return false;
+        }
+
+        File[] sourceFiles = sourceFile.listFiles();
+        if (null == sourceFiles || sourceFiles.length < 1) {
+            logger.error("待压缩的文件目录:" + sourceFilePath + "里面不存在文件,无需压缩.");
+            return false;
+        }
+
+        try (
+                FileOutputStream fos = new FileOutputStream(zipFile);
+                BufferedOutputStream bos = new BufferedOutputStream(fos);
+                ZipOutputStream zos = new ZipOutputStream(bos);
+        ) {
+
+            byte[] bytes = new byte[1024 * 10];
+            for (int i = 0; i < sourceFiles.length; i++) {
+                File file = sourceFiles[i];
+                if (!file.isFile()) {
+                    continue;
+                }
+
+                try (
+                        FileInputStream fis = new FileInputStream(file);
+                        BufferedInputStream bis = new BufferedInputStream(fis, 1024 * 10);
+                ) {
+                    //创建ZIP实体,并添加进压缩包
+                    String fileEncode = System.getProperty("file.encoding");
+                    String name = new String(file.getName().getBytes(fileEncode), "UTF-8");
+
+                    ZipEntry zipEntry = new ZipEntry(name);
+                    zos.putNextEntry(zipEntry);
+
+                    //读取待压缩的文件并写进压缩包里
+                    int read;
+                    while ((read = bis.read(bytes, 0, 1024 * 10)) != -1) {
+                        zos.write(bytes, 0, read);
                     }
+
+                    zos.flush();
+                } catch (Exception e) {
+                    logger.error(e.getMessage(), e);
                 }
-            } catch (Exception e) {
-                logger.error(e.getMessage(), e);
-            } finally {
-                IOUtils.closeQuietly(bis);
-                IOUtils.closeQuietly(fis);
-                IOUtils.closeQuietly(zos);
-                IOUtils.closeQuietly(fos);
             }
+
+            logger.info("压缩" + sourceFilePath + "目录完成");
+            return true;
+        } catch (Exception e) {
+            logger.error(e.getMessage(), e);
         }
-        logger.info("压缩" + sourceFilePath + "目录完成");
-        return flag;
+
+        return false;
     }
 
     public static void createDirectory(String downloadDirectory) {

+ 44 - 23
examcloud-core-questions-base/src/main/java/cn/com/qmth/examcloud/core/questions/base/ZipUtils.java

@@ -1,14 +1,16 @@
 package cn.com.qmth.examcloud.core.questions.base;
 
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.*;
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipOutputStream;
 
 public class ZipUtils {
-    public static void doCompress(String srcFile, String zipFile) throws Exception {
+    private static final Logger log = LoggerFactory.getLogger(ZipUtils.class);
+
+    public static void doCompress(String srcFile, String zipFile) {
         doCompress(new File(srcFile), new File(zipFile));
     }
 
@@ -18,36 +20,55 @@ public class ZipUtils {
      * @param srcFile  目录或者单个文件
      * @param destFile 压缩后的ZIP文件
      */
-    public static void doCompress(File srcFile, File destFile) throws Exception {
-        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(destFile));
-        if (srcFile.isDirectory()) {
-            File[] files = srcFile.listFiles();
-            for (File file : files) {
-                doCompress(file, out);
+    public static void doCompress(File srcFile, File destFile) {
+        try (FileOutputStream fos = new FileOutputStream(destFile);
+             ZipOutputStream out = new ZipOutputStream(fos);) {
+
+            if (srcFile.isDirectory()) {
+                File[] files = srcFile.listFiles();
+                for (File file : files) {
+                    doCompress(file, out);
+                }
+            } else {
+                doCompress(srcFile, out);
             }
-        } else {
-            doCompress(srcFile, out);
+        } catch (FileNotFoundException e) {
+            log.error(e.getMessage(), e);
+        } catch (IOException e) {
+            log.error(e.getMessage(), e);
         }
     }
 
-    public static void doCompress(String pathname, ZipOutputStream out) throws IOException {
+    public static void doCompress(String pathname, ZipOutputStream out) {
         doCompress(new File(pathname), out);
     }
 
-    public static void doCompress(File file, ZipOutputStream out) throws IOException {
-        if (file.exists()) {
+    public static void doCompress(File file, ZipOutputStream out) {
+        if (!file.exists()) {
+            return;
+        }
+
+        try (FileInputStream fis = new FileInputStream(file);) {
+            ZipEntry entry = new ZipEntry(file.getName());
+            out.putNextEntry(entry);
+
             byte[] buffer = new byte[1024];
-            FileInputStream fis = new FileInputStream(file);
-            out.putNextEntry(new ZipEntry(file.getName()));
-            int len = 0;
-            // 读取文件的内容,打包到zip文件    
+            int len;
+            // 读取文件的内容,打包到zip文件
             while ((len = fis.read(buffer)) > 0) {
                 out.write(buffer, 0, len);
             }
+
             out.flush();
-            out.closeEntry();
-            fis.close();
+        } catch (IOException e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            try {
+                out.closeEntry();
+            } catch (IOException e) {
+                //ignore
+            }
         }
     }
 
-}
+}

+ 32 - 28
examcloud-core-questions-base/src/main/java/cn/com/qmth/examcloud/core/questions/base/converter/utils/FileUtil.java

@@ -289,7 +289,7 @@ public class FileUtil {
      * @param targetDir 解压目录
      * @param zipFile   待解压的ZIP文件
      */
-    public static List<File> unZip(File targetDir, File zipFile) throws IOException {
+    public static List<File> unZip(File targetDir, File zipFile) {
         if (targetDir == null) {
             log.error("解压目录不能为空!");
             return null;
@@ -318,37 +318,41 @@ public class FileUtil {
         log.info("UnZip targetDir:" + targetDir.getAbsolutePath());
         List<File> result = new LinkedList<>();
 
-        ZipFile zip = new ZipFile(zipFile, Charset.forName("UTF-8"));
-        Enumeration entries = zip.entries();
-        while (entries.hasMoreElements()) {
-            ZipEntry entry = (ZipEntry) entries.nextElement();
-
-            //Linux中需要替换掉路径的反斜杠
-            String entryName = (File.separator + entry.getName()).replaceAll("\\\\", "/");
-            log.info("UnZip:" + entryName);
-
-            String filePath = targetDir.getAbsolutePath() + entryName;
-            File target = new File(filePath);
-            if (entry.isDirectory()) {
-                target.mkdirs();
-            } else {
-                File dir = target.getParentFile();
-                if (!dir.exists()) {
-                    dir.mkdirs();
-                }
-
-                try (OutputStream os = new FileOutputStream(target);
-                     InputStream is = zip.getInputStream(entry);) {
-                    IOUtils.copy(is, os);
-                    os.flush();
-                } catch (IOException e) {
-                    log.error(e.getMessage(), e);
+        try (ZipFile zip = new ZipFile(zipFile, Charset.forName("UTF-8"));) {
+
+            Enumeration entries = zip.entries();
+            while (entries.hasMoreElements()) {
+                ZipEntry entry = (ZipEntry) entries.nextElement();
+
+                //Linux中需要替换掉路径的反斜杠
+                String entryName = (File.separator + entry.getName()).replaceAll("\\\\", "/");
+                log.info("UnZip:" + entryName);
+
+                String filePath = targetDir.getAbsolutePath() + entryName;
+                File target = new File(filePath);
+                if (entry.isDirectory()) {
+                    target.mkdirs();
+                } else {
+                    File dir = target.getParentFile();
+                    if (!dir.exists()) {
+                        dir.mkdirs();
+                    }
+
+                    try (OutputStream os = new FileOutputStream(target);
+                         InputStream is = zip.getInputStream(entry);) {
+                        IOUtils.copy(is, os);
+                        os.flush();
+                    } catch (IOException e) {
+                        log.error(e.getMessage(), e);
+                    }
+                    result.add(target);
                 }
-                result.add(target);
             }
+
+        } catch (IOException e) {
+            log.error(e.getMessage(), e);
         }
 
-        zip.close();
         return result;
     }
 

+ 9 - 5
examcloud-core-questions-base/src/main/java/cn/com/qmth/examcloud/core/questions/base/word/DocxProcessUtil.java

@@ -881,11 +881,16 @@ public final class DocxProcessUtil {
         response.setHeader("Content-Disposition", "attachment; filename=" + new String(zipFileName.getBytes("UTF-8"), "iso-8859-1") + ".zip");
         // 设置强制下载不打开
         response.setContentType("application/octet-stream;charset=utf-8");
-        ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
-        for (String fileName : fileNames) {
-            ZipUtils.doCompress(TEMP_FILE_EXP + fileName, out);
-            response.flushBuffer();
+
+        try (ZipOutputStream out = new ZipOutputStream(response.getOutputStream());) {
+            for (String fileName : fileNames) {
+                ZipUtils.doCompress(TEMP_FILE_EXP + fileName, out);
+                response.flushBuffer();
+            }
+        } catch (IOException e) {
+            logger.error(e.getMessage(), e);
         }
+
         //删除本地文件
         for (String fileName : fileNames) {
             File file = new File(TEMP_FILE_EXP + fileName);
@@ -893,7 +898,6 @@ public final class DocxProcessUtil {
                 IoUtils.removeFile(file);
             }
         }
-        out.close();
     }
 
     /**