Description
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).
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); } } }
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
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
if (exists() && !isSameFile(file)) {
deleteSelf();
}
But I think that the problem is in the DefaultFileContent.write methods
Attachments
Issue Links
- is fixed by
-
VFS-807 LocalFile migration to NIO is not done correctly
- Resolved