【问题标题】:Preserve file last modified date time while copying it from source to target在将文件从源复制到目标时保留文件的上次修改日期时间
【发布时间】:2020-02-16 07:02:00
【问题描述】:

我正在尝试将文件从一个位置复制到另一个位置。在将其从源复制到目标时,目标文件正在占用当前日期时间。如何使目标文件日期与源文件相同。

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();`

【问题讨论】:

标签: java file java-8 fileinputstream fileoutputstream


【解决方案1】:

这是由java.io.File 类提供的。您需要先创建它的一个实例并将其传递给流:

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);

顺便说一句:我假设您至少使用 Java 7,所以我更改了您的代码以使用 try-with-resources 功能。强烈建议这样做,因为它还负责在引发异常时关闭资源。

【讨论】:

  • 你知道java.nio.file.Files类及其copy()方法吗?该类是在 JDK 7 中添加的。
【解决方案2】:

从 JDK 7 开始,以下代码将复制文件,复制的文件将具有与原始文件相同的属性,这意味着目标文件将与源文件具有相同的日期。

java.nio.file.Path source = java.nio.file.Paths.get("D:\\test\\test.txt");
java.nio.file.Path target = java.nio.file.Paths.get("D:\\test.txt");
try {
    java.nio.file.Files.copy(source, target, java.nio.file.StandardCopyOption.COPY_ATTRIBUTES);
}
catch (java.io.IOException x) {
    x.printStackTrace();
}

【讨论】:

    【解决方案3】:

    如果可以,请使用 Path API。

    例如要在新文件中保留原文件的所有属性,请使用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
    }
    

    StandardCopyOption.COPY_ATTRIBUTES 枚举状态:

    至少,最后修改时间被复制到目标文件,如果 源文件存储和目标文件存储都支持。

    如果你只想复制最后修改的时间属性,那并不复杂,只需在复制后添加该设置并删除CopyOption arg 例如:

    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
    }
    

    最后,注意Path和File是可以互操作的:Path.toFile()返回对应的FileFile.toPath()返回对应的Path
    因此,即使您将Files 作为输入进行操作,实现仍可能使用Path API 而不会破坏它。

    【讨论】:

      猜你喜欢
      • 2016-05-28
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 1970-01-01
      • 1970-01-01
      • 2013-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多