Răsfoiți Sursa

修改IOUtils中纯文件拷贝的实现方式,并附带测试代码

Signed-off-by: luoshi <luoshi@qmth.com.cn>
luoshi 3 ani în urmă
părinte
comite
4be8910766

+ 4 - 9
tools-common/src/main/java/com/qmth/boot/tools/io/IOUtils.java

@@ -2,7 +2,8 @@ package com.qmth.boot.tools.io;
 
 import java.io.*;
 import java.nio.channels.FileChannel;
-import java.nio.file.StandardOpenOption;
+import java.nio.file.Files;
+import java.nio.file.StandardCopyOption;
 
 public class IOUtils {
 
@@ -34,11 +35,9 @@ public class IOUtils {
     }
 
     public static long copy(InputStream input, OutputStream output, BufferListener listener) throws IOException {
-        byte[] buffer = new byte[4096];
         long count = 0L;
-
         int n;
-        for (boolean r = false; -1 != (n = input.read(buffer)); count += (long) n) {
+        for (byte[] buffer = new byte[4096]; -1 != (n = input.read(buffer)); count += n) {
             if (output != null) {
                 output.write(buffer, 0, n);
             }
@@ -54,11 +53,7 @@ public class IOUtils {
     }
 
     public static void copy(File source, File target) throws IOException {
-        FileChannel inc = FileChannel.open(source.toPath(), StandardOpenOption.READ);
-        FileChannel ouc = FileChannel.open(target.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
-        inc.transferTo(0, inc.size(), ouc);
-        inc.close();
-        ouc.close();
+        Files.copy(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING);
     }
 
     public static byte[] toByteArray(InputStream ins) throws IOException {

+ 16 - 0
tools-common/src/test/java/com/qmth/boot/test/tools/io/IOUtilsTest.java

@@ -0,0 +1,16 @@
+package com.qmth.boot.test.tools.io;
+
+import com.qmth.boot.tools.io.IOUtils;
+
+import java.io.File;
+import java.io.IOException;
+
+public class IOUtilsTest {
+
+    //@Test
+    public void test() throws IOException {
+        File source = new File("/Users/luoshi/Downloads/1654743335639.json");
+        File target = new File("/Users/luoshi/Downloads/11-3-copy.json");
+        IOUtils.copy(source, target);
+    }
+}