Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ public abstract class FileCopyUtils {

/**
* Copy the contents of the given input File to the given output File.
* <p>If both refer to the same file, nothing is copied and the file is left
* unchanged, like {@link Files#copy(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...)}.
* @param in the file to copy from
* @param out the file to copy to
* @return the number of bytes copied
Expand All @@ -64,6 +66,10 @@ public abstract class FileCopyUtils {
public static int copy(File in, File out) throws IOException {
Assert.notNull(in, "No input File specified");
Assert.notNull(out, "No output File specified");
if (out.exists() && Files.isSameFile(in.toPath(), out.toPath())) {
// Opening the output stream would truncate the input
return 0;
}
return copy(Files.newInputStream(in.toPath()), Files.newOutputStream(out.toPath()));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,18 @@ void copyFileToByteArray(@TempDir Path tempDir) throws IOException {
assertThat(FileCopyUtils.copyToByteArray(source.toFile())).asString().isEqualTo("content");
}

@Test
void copyFileToSameFile(@TempDir Path tempDir) throws IOException {
Path source = tempDir.resolve("src");
Files.write(source, "content".getBytes());
assertThat(FileCopyUtils.copy(source.toFile(), source.toFile())).isZero();
assertThat(source).content().isEqualTo("content");
Path sameFile = tempDir.resolve("sub").resolve("..").resolve("src");
Files.createDirectory(tempDir.resolve("sub"));
assertThat(FileCopyUtils.copy(source.toFile(), sameFile.toFile())).isZero();
assertThat(source).content().isEqualTo("content");
}

@Test
void copyByteArrayToFile(@TempDir Path tempDir) throws IOException {
Path target = tempDir.resolve("target");
Expand Down