Just use the Path API if you may.
For example to keep all attributes of the original file in the new file, use Files.copy(Path source, Path target, CopyOption... options)
:
try {
Path copiedFile =
Files.copy(Paths.get("D:\\test\\test.txt"), Paths.get("D:\\test.txt"),
StandardCopyOption.COPY_ATTRIBUTES);
}
catch (IOException e){
// handle that
}
The StandardCopyOption.COPY_ATTRIBUTES
enum states :
Minimally, the last-modified-time is copied to the target file if
supported by both the source and target file stores.
If you want to copy only the last-modified time attribute, that is not more complicated, just add that setting after the copy and remove the CopyOption
arg such as :
Path originalFile = Paths.get("D:\\test.txt")
try {
Path copiedFile =
Files.copy(Paths.get("D:\\test\\test.txt"), originalFile);
Files.setLastModifiedTime(copiedFile,
Files.getLastModifiedTime(originalFile));
}
catch (IOException e){
// handle that
}
At last, note that Path and File are interoperable : Path.toFile()
returns the corresponding File
and File.toPath()
returns the corresponding Path
.
So even if you manipulate File
s as input, the implementation may still use the Path
API without breaking that.