Anthony Goubard created VFS-820:
-----------------------------------
Summary: FileObject.copyFrom leaves extra bytes when copying from
a smaller file
Key: VFS-820
URL: https://issues.apache.org/jira/browse/VFS-820
Project: Commons VFS
Issue Type: Bug
Affects Versions: 2.9.0
Environment: Tested on Windows 10
Reporter: Anthony Goubard
If you copy a file using the _FileObject.copyFrom_ method and the destination
file is larger than the source file, the destination will contain the bytes of
the source file and the remaining bytes of the destination (See example).
{code:java}
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.VFS;
public class BugCopyToLargerFile {
private static final String LARGE_TEXT = "This is a larger text.\nTo show
that the extra bytes are remining after a copy of a small file";
private static final String SHORT_TEXT = "This is a short text.";
public static final void main(String args[]) throws IOException {
File largeFile = new File(System.getProperty("java.io.tmpdir"),
"large.txt");
File shortFile = new File(System.getProperty("java.io.tmpdir"),
"short.txt");
FileObject largeFileObject = VFS.getManager().toFileObject(largeFile);
Files.writeString(largeFile.toPath(), LARGE_TEXT,
StandardCharsets.UTF_8);
FileObject shortFileObject = VFS.getManager().toFileObject(shortFile);
Files.writeString(shortFile.toPath(), SHORT_TEXT,
StandardCharsets.UTF_8);
checkFileContent(shortFile, SHORT_TEXT);
checkFileContent(largeFile, LARGE_TEXT);
largeFileObject.copyFrom(shortFileObject, Selectors.SELECT_ALL);
checkFileContent(largeFile, SHORT_TEXT);
}
private static void checkFileContent(File file, String content) throws
IOException {
String fileContent = Files.readString(file.toPath(),
StandardCharsets.UTF_8);
if (fileContent.equals(content)) {
System.out.println(file.getName() + " correct");
} else {
System.out.println(file.getName() + " incorrect content: " +
fileContent);
}
}
}
{code}
{noformat}
short.txt correct
large.txt correct
large.txt incorrect content: This is a short text..
To show that the extra bytes are remining after a copy of a small file
{noformat}
Note that the javadoc of copyFrom contains "If this file does exist, it is
deleted first." but it doesn't happen in the code.
One solution would be to delete the file like in _FileObject.moveTo_ method
{code:java}
if (exists() && !isSameFile(file)) {
deleteSelf();
}
{code}
But I think that the problem is in the _DefaultFileContent.write_ methods
--
This message was sent by Atlassian Jira
(v8.20.7#820007)