Search code examples
javafilejava-8fileinputstreamfileoutputstream

Preserve file last modified date time while copying it from source to target


I am trying to copy a file from one location to another. While copying it from source to target, target file is taking current date time. How can i make target file date as same as source file.

FileInputStream source = new FileInputStream("D:\\test\\test.txt");
OutputStream target = new FileOutputStream("D:\\test.txt");
byte[] buffer = new byte[source.available()];
source.read(buffer);
target.write(buffer);
source.close();
target.close();`

Solution

  • This is provided by the java.io.File class. You need to create an instance of it first and pass it to the streams:

    File input = new File("D:\\test\\test.txt");
    File output = new File("D:\\test.txt");
    try( FileInputStream source = new FileInputStream(input);
         OutputStream target = new FileOutputStream(output)){
        byte[] buffer = new byte[source.available()];
        source.read(buffer);
        target.write(buffer);
    }
    long modified = input.lastModified();
    output.setLastModified(modified);
    

    BTW: I assume you use at least Java 7, so I changed your code to use the try-with-resources feature. This is strongly recommended since it also takes care of closing resources in case an exception is raised.