Skip to content

Do not truncate the source in FileCopyUtils.copy(File, File) for the same file - #37718

Open
Marti2203 wants to merge 1 commit into
spring-projects:mainfrom
Marti2203:filecopyutils-same-file
Open

Marti2203 wants to merge 1 commit into
spring-projects:mainfrom
Marti2203:filecopyutils-same-file

Conversation

@Marti2203

Copy link
Copy Markdown

FileCopyUtils.copy(File, File) opens the input stream and then the output stream. When both arguments refer to the same file (the same path, or another path to it), opening the output truncates the file before anything is read, so the method returns 0 and the file is left empty:

File f = ...;                  // 17 bytes
FileCopyUtils.copy(f, f);      // returns 0, f is now 0 bytes

This change detects the case with Files.isSameFile() and leaves the file unchanged, which is what Files.copy() does when the source and target are the same file. A new test, FileCopyUtilsTests.copyFileToSameFile, covers the same path and a sub/../src path to the same file; it fails before the change and passes after it.

Testing: FileCopyUtilsTests (10 tests), :spring-core:checkstyleMain and checkstyleTest pass. 7.0.x and 6.2.x have the same code.

The issue was found by an LLM-assisted tool and verified manually.

…same file

FileCopyUtils.copy(File, File) opens the input stream and then the output
stream. When both refer to the same file (same path, or a different path
to it), opening the output truncates the file before anything is read:
the method returns 0 and the file is left empty.

Detect this case with Files.isSameFile() and leave the file unchanged,
which is what Files.copy() does for the same source and target.

Signed-off-by: Martin Mirchev <mmirchev@comp.nus.edu.sg>
@spring-projects-issues spring-projects-issues added the status: waiting-for-triage An issue we've not yet triaged or decided on label Nov 18, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: waiting-for-triage An issue we've not yet triaged or decided on

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants