diff --git a/spring-core/src/main/java/org/springframework/util/FileCopyUtils.java b/spring-core/src/main/java/org/springframework/util/FileCopyUtils.java index 20e36f79c49e..52289dbf4c63 100644 --- a/spring-core/src/main/java/org/springframework/util/FileCopyUtils.java +++ b/spring-core/src/main/java/org/springframework/util/FileCopyUtils.java @@ -56,6 +56,8 @@ public abstract class FileCopyUtils { /** * Copy the contents of the given input File to the given output File. + *

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 @@ -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())); } diff --git a/spring-core/src/test/java/org/springframework/util/FileCopyUtilsTests.java b/spring-core/src/test/java/org/springframework/util/FileCopyUtilsTests.java index 87d1b1140570..19edf161f7e1 100644 --- a/spring-core/src/test/java/org/springframework/util/FileCopyUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/FileCopyUtilsTests.java @@ -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");