Login  Register

Re: File.copy while preserving the modification date

Posted by Wayne Rasband-2 on Mar 25, 2018; 10:46pm
URL: http://imagej.273.s1.nabble.com/Problem-with-Maximum-intensity-projection-tp5020309p5020334.html

> On Mar 25, 2018, at 11:16 AM, Norbert Vischer <[hidden email]> wrote:
>
> Hello all,
>
> when using:
>
> File.copy(path1, path2);
>
> the modification date of the the copied file changes to "now".
> This is not correct and misleading, as the file content was not changed.
>
> When going to:
> https://stackoverflow.com/questions/21215883/preserve-file-creation-time-with-java
> I find the method:
> Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES);
> which should be supported from Java 7,
> However, I did not succeed to get it work
>
> My questions:
>
> a) wouldn't it make sense that the File.copy method preserves the modification date?

In the latest daily build (1.52a17), the File.copy() macro function preserves the modification date.

> b) Is there somewhere a working Java snippet that I can get working?

File.copy() uses the Tools.copyFile() method, reproduced below.

-wayne

   /** Copies the contents of the file at 'path1' to 'path2', returning an error message
      (as a non-empty string) if there is an error. Based on the method with the
      same name in Tobias Pietzsch's TifBenchmark class.
   */
   public static String copyFile(String path1, String path2) {
      File f1 = new File(path1);
      File f2 = new File(path2);
      try {
         if (!f1.exists() )
            return "Source file does not exist";
         if (!f2.exists() )
            f2.createNewFile();
         long time = f1.lastModified();  
         FileInputStream stream1 = new FileInputStream(f1);
         FileChannel channel1 = stream1.getChannel();
         FileOutputStream stream2 = new FileOutputStream(f2);
         final FileChannel channel2 = stream2.getChannel();
         if (channel2!=null && channel1!=null )
            channel2.transferFrom(channel1, 0, channel1.size());
         channel1.close();
         stream1.close();
         channel2.close();
         stream2.close();  
         f2.setLastModified(time);
      } catch(Exception e) {
         return e.getMessage();
      }
      return "";
   }
--
ImageJ mailing list: http://imagej.nih.gov/ij/list.html