소스 검색

Use try-with-resources close io streams

deason 5 년 전
부모
커밋
4120faf0a8
1개의 변경된 파일72개의 추가작업 그리고 61개의 파일을 삭제
  1. 72 61
      examcloud-core-questions-base/src/main/java/cn/com/qmth/examcloud/core/questions/base/converter/utils/FileUtil.java

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

@@ -7,6 +7,7 @@
 
 package cn.com.qmth.examcloud.core.questions.base.converter.utils;
 
+import cn.com.qmth.examcloud.core.questions.base.IoUtils;
 import org.apache.commons.io.IOUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -31,34 +32,31 @@ public class FileUtil {
      * @return
      */
     public static File cutFile(String sourcePath, String targetPath, int n) {
-        FileInputStream fis = null;
-        InputStream is = null;
-        OutputStream os = null;
-        try {
-            File file = new File(sourcePath);
-            fis = new FileInputStream(file);
+        File file = new File(sourcePath);
+        File newFile = new File(targetPath);
+
+        try (
+                FileInputStream fis = new FileInputStream(file);
+                InputStream is = new BufferedInputStream(fis);
+                OutputStream os = new FileOutputStream(newFile);
+        ) {
+
             //从n个字节开始读,注意中文是两个字节
             fis.skip(n);
-            //指定文件位置读取的文件流
-            is = new BufferedInputStream(fis);
-            //存入新文件
-            File newFile = new File(targetPath);
-            os = new FileOutputStream(newFile);
+
+            //指定文件位置读取的文件流,存入新文件
             byte buffer[] = new byte[4 * 1024];
             int len;
             while ((len = is.read(buffer)) != -1) {
                 os.write(buffer, 0, len);
             }
+
             os.flush();
             return newFile;
         } catch (FileNotFoundException e) {
             log.error(e.getMessage(), e);
         } catch (IOException e) {
             log.error(e.getMessage(), e);
-        } finally {
-            IOUtils.closeQuietly(fis);
-            IOUtils.closeQuietly(is);
-            IOUtils.closeQuietly(os);
         }
         return null;
     }
@@ -74,16 +72,17 @@ public class FileUtil {
     public static String[] readFileHeader(String path, int headerSize, int signSize) {
         int n = headerSize / 2;
         String[] codes = new String[n + 1];
-        FileInputStream fis = null;
-        DataInputStream ois = null;
-        try {
-            File file = new File(path);
-            fis = new FileInputStream(file);
-            ois = new DataInputStream(fis);
+
+        File file = new File(path);
+        try (
+                FileInputStream fis = new FileInputStream(file);
+                DataInputStream ois = new DataInputStream(fis);
+        ) {
             //分n次读取文件(n * 2)个字节
             for (int i = 0; i < n; i++) {
                 codes[i] = String.valueOf(ois.readShort());
             }
+
             if (signSize > 0) {
                 StringBuilder ss = new StringBuilder();
                 for (int i = 0; i < signSize; i++) {
@@ -95,10 +94,8 @@ public class FileUtil {
             log.error(e.getMessage(), e);
         } catch (IOException e) {
             log.error(e.getMessage(), e);
-        } finally {
-            IOUtils.closeQuietly(fis);
-            IOUtils.closeQuietly(ois);
         }
+
         return codes;
     }
 
@@ -135,16 +132,18 @@ public class FileUtil {
      * 在文件流前面追加头信息和签名信息,并生成新的“.tk”文件
      */
     public static boolean appendHeader(File file, short[] headers, String sign) {
-        FileInputStream fis = null;
-        InputStream is = null;
-        FileOutputStream fos = null;
-        DataOutputStream dos = null;
         if (file == null || !file.exists()) {
             return false;
         }
+
         if (!file.isFile()) {
             return false;
         }
+
+        FileInputStream fis = null;
+        InputStream is = null;
+        FileOutputStream fos = null;
+        DataOutputStream dos = null;
         try {
             //创建临时文件
             String baseFilePath = file.getAbsolutePath();
@@ -152,6 +151,7 @@ public class FileUtil {
             File newFile = new File(targetFilePath);
             fos = new FileOutputStream(newFile);
             dos = new DataOutputStream(fos);
+
             //写入头信息
             for (short s : headers) {
                 dos.writeShort(s);
@@ -160,9 +160,11 @@ public class FileUtil {
                 //写入签名信息
                 dos.write(sign.getBytes("ISO-8859-1"));
             }
+
             //在临时文件中追加原始文件内容
             fis = new FileInputStream(file);
             is = new BufferedInputStream(fis);
+
             byte buffer[] = new byte[4 * 1024];
             int len;
             while ((len = is.read(buffer)) != -1) {
@@ -258,33 +260,26 @@ public class FileUtil {
             encoding = "UTF-8";
         }
 
-        BufferedWriter bw = null;
-        try {
-            File file = new File(path);
-            if (!file.exists()) {
-                if (FileUtil.makeDirs(file.getParent())) {
-                    boolean ok = file.createNewFile();
-                    if (!ok) {
-                        throw new RuntimeException("文件创建失败!");
-                    }
+        File file = new File(path);
+        if (!file.exists()) {
+            if (FileUtil.makeDirs(file.getParent())) {
+                boolean ok = IoUtils.createFile(file);
+                if (!ok) {
+                    throw new RuntimeException("文件创建失败!");
                 }
             }
+        }
 
-            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file), encoding);
-            bw = new BufferedWriter(write);
+        try (
+                FileOutputStream fos = new FileOutputStream(file);
+                OutputStreamWriter write = new OutputStreamWriter(fos, encoding);
+                BufferedWriter bw = new BufferedWriter(write);
+        ) {
             bw.write(content);
+            bw.flush();
             log.info("save as file success. " + path);
         } catch (IOException e) {
             log.error("save as file error. " + path);
-        } finally {
-            try {
-                if (bw != null) {
-                    bw.flush();
-                    bw.close();
-                }
-            } catch (IOException e) {
-                log.error(e.getMessage(), e);
-            }
         }
     }
 
@@ -299,31 +294,39 @@ public class FileUtil {
             log.error("解压目录不能为空!");
             return null;
         }
+
         if (zipFile == null) {
             log.error("待解压的文件不能为空!");
             return null;
         }
+
         if (!zipFile.exists()) {
             log.error("待解压的文件不存在!" + zipFile.getAbsolutePath());
             return null;
         }
+
         String zipName = zipFile.getName().toLowerCase();
         if (zipFile.isDirectory() || zipName.indexOf(".zip") < 0) {
             log.error("待解压的文件格式错误!");
             return null;
         }
+
         if (!targetDir.exists()) {
             targetDir.mkdir();
         }
+
         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()) {
@@ -333,15 +336,18 @@ public class FileUtil {
                 if (!dir.exists()) {
                     dir.mkdirs();
                 }
-                OutputStream os = new FileOutputStream(target);
-                InputStream is = zip.getInputStream(entry);
-                IOUtils.copy(is, os);
-                os.flush();
-                IOUtils.closeQuietly(os);
-                IOUtils.closeQuietly(is);
+
+                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);
             }
         }
+
         zip.close();
         return result;
     }
@@ -357,6 +363,7 @@ public class FileUtil {
             log.error("目录或文件不能为空!");
             return false;
         }
+
         if (zipFile == null) {
             log.error("待压缩的文件不能为空!");
             return false;
@@ -399,9 +406,11 @@ public class FileUtil {
         if (parentDir == null) {
             parentDir = "";
         }
+
         if (!"".equals(parentDir) && !parentDir.endsWith(File.separator)) {
             parentDir += File.separator;
         }
+
         if (target.isDirectory()) {
             File[] files = target.listFiles();
             if (files.length > 0) {
@@ -413,14 +422,16 @@ public class FileUtil {
                 zipOutStream.closeEntry();
             }
         } else {
-            InputStream is = new FileInputStream(target);
-            zipOutStream.putNextEntry(new ZipEntry(parentDir + target.getName()));
-            int len = 0;
-            byte[] bytes = new byte[1024];
-            while ((len = is.read(bytes)) > 0) {
-                zipOutStream.write(bytes, 0, len);
+            try (InputStream is = new FileInputStream(target);) {
+                zipOutStream.putNextEntry(new ZipEntry(parentDir + target.getName()));
+                int len;
+                byte[] bytes = new byte[1024];
+                while ((len = is.read(bytes)) > 0) {
+                    zipOutStream.write(bytes, 0, len);
+                }
+            } catch (IOException e) {
+                log.error(e.getMessage(), e);
             }
-            IOUtils.closeQuietly(is);
             zipOutStream.closeEntry();
         }
     }