Skip to content

Commit

Permalink
Added FileUtils.copy with callback for written bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
Aklakan committed Feb 2, 2025
1 parent f2cf55d commit 11ae7c8
Showing 1 changed file with 26 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.aksw.commons.io.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
Expand All @@ -26,6 +27,7 @@
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntConsumer;
import java.util.stream.Stream;

import org.aksw.commons.lambda.throwing.ThrowingConsumer;
Expand Down Expand Up @@ -424,4 +426,28 @@ protected static void copyDirectoryInternal(Path source, Path target, CopyOption
}
}
}

// Adaption of Files.copy and InputStream.transfer to with progress tracking

private static final int DEFAULT_BUFFER_SIZE = 8192;

public static long copy(Path source, OutputStream out, IntConsumer contribCallback) throws IOException {
Objects.requireNonNull(out);
try (InputStream in = Files.newInputStream(source)) {
return transferTo(out, in, contribCallback);
}
}

public static long transferTo(OutputStream out, InputStream in, IntConsumer contribCallback) throws IOException {
Objects.requireNonNull(out, "out");
long transferred = 0;
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int read;
while ((read = in.read(buffer, 0, DEFAULT_BUFFER_SIZE)) >= 0) {
out.write(buffer, 0, read);
transferred += read;
contribCallback.accept(read);
}
return transferred;
}
}

0 comments on commit 11ae7c8

Please sign in to comment.