Procházet zdrojové kódy

IOStreams: copy slice

Mariusz Sieroń před 6 roky
rodič
revize
94f6141f24

+ 29 - 0
assira/src/main/java/net/ranides/assira/io/IOStreams.java

@@ -54,6 +54,10 @@ public final class IOStreams {
         return copy(input, output, null);
     }
 
+    public static long copy(InputStream input, OutputStream output, long size) throws IOException {
+        return copy(input, output, size, null);
+    }
+
     public static long copy(InputStream input, OutputStream output, Consumer<Long> callback) throws IOException {
         byte[] buffer = new byte[COPY_BUFFER];
         int n;
@@ -67,6 +71,31 @@ public final class IOStreams {
         }
         return s;
     }
+
+    public static long copy(InputStream input, OutputStream output, final long size, Consumer<Long> callback) throws IOException {
+        byte[] buffer = new byte[COPY_BUFFER];
+
+        long remaining = size;
+        while (true) {
+            int n = buffer.length < remaining ? buffer.length : (int) remaining;
+
+            n = input.read(buffer, 0, n);
+            if (n < 0) {
+                return size - remaining;
+            }
+            output.write(buffer, 0, n);
+
+            if(null != callback) {
+                callback.accept((long)n);
+            }
+
+            remaining -= n;
+
+            if (remaining == 0L) {
+                return size;
+            }
+        }
+    }
     
     public static boolean equivalent(InputStream stream1, InputStream stream2) throws IOException {
         return equivalent(stream1, stream2, COPY_BUFFER);

+ 17 - 1
assira/src/test/java/net/ranides/assira/io/IOStreamsTest.java

@@ -29,6 +29,8 @@ import java.nio.charset.MalformedInputException;
 import java.util.*;
 import java.util.function.Predicate;
 import java.util.stream.Collectors;
+
+import net.ranides.assira.collection.arrays.ArrayUtils;
 import net.ranides.assira.events.EventDispatcher;
 import net.ranides.assira.events.EventRouter;
 import net.ranides.assira.functional.CheckedFunction;
@@ -60,7 +62,21 @@ public class IOStreamsTest {
         assertCopy(7* 4096 + 1);
         assertCopy(7* 4096 + 740);
     }
-    
+
+    @Test
+    public void testCopy2() throws IOException {
+        byte[] data = random(32, 777L);
+        ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
+        ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
+
+        ByteArrayInputStream bis = new ByteArrayInputStream(data);
+        IOStreams.copy(bis, bos1, 16);
+        IOStreams.copy(bis, bos2, 14);
+
+        assertArrayEquals(ArrayUtils.slice(data, 0, 16), bos1.toByteArray());
+        assertArrayEquals(ArrayUtils.slice(data, 16, 30), bos2.toByteArray());
+    }
+
     @Test
     public void testEquivalent() throws IOException {
         byte[] data1 = random(7*4096+33, 777L);