使用Java中的jimfs设置文件的最后修改时间戳

5
我该如何使用jimfs设置文件的最后修改日期? 我有类似这样的代码:
final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());
Path rootPath = Files.createDirectories(fileSystem.getPath("root/path/to/directory"));
Path filePath = rootPath.resolve("test1.pdf");
Path anotherFilePath = rootPath.resolve("test2.pdf");

在创建完所需内容后,我会创建一个目录迭代器,如下所示:
try (final DirectoryStream<Path> dirStream = Files.newDirectoryStream(rootPath, "*.pdf")) {
 final Iterator<Path> pathIterator = dirStream.iterator();
}

然后我遍历文件并读取最后修改的文件,然后将其返回:

Path resolveLastModified(Iterator<Path> dirStreamIterator){
    long lastModified = Long.MIN_VALUE;
    File lastModifiedFile = null;
    while (dirStreamIterator.hasNext()) {
        File file = new File(dirStreamIterator.next().toString());
        final long actualLastModified = file.lastModified();
        if (actualLastModified > lastModified) {
            lastModifiedFile = file;
            lastModified = actualLastModified;
        }
    }
    return lastModifiedFile.toPath();
}

问题在于两个文件 "test1.pdf" 和 "test2.pdf" 的 lastModified 都是 "0",因此我实际上无法测试行为,因为该方法总是返回目录中的第一个文件。我尝试过执行以下操作:
File file = new File(filePath.toString());
file.setLastModified(1);

但是该方法返回false

更新

我刚看到File#getLastModified()使用默认文件系统。这意味着将使用默认的本地文件系统来读取时间戳。这意味着我无法使用Jimfs创建临时文件,读取最后修改的时间戳,然后断言这些文件的路径。其中一个将具有jimfs://作为URI方案,另一个将具有依赖于操作系统的方案。


https://dev59.com/E27Xa4cB1Zd3GeqPq4gw - Jayan
2个回答

9

Jimfs使用Java 7文件API。它与旧的File API不太兼容,因为File对象始终绑定到默认文件系统。所以不要使用File

如果您有一个Path,应该使用java.nio.file.Files类对其进行大多数操作。在这种情况下,您只需要使用

Files.setLastModifiedTime(path, FileTime.fromMillis(millis));

非常感谢,它完美地解决了问题。现在我又可以使用jimfs了。你救了我一命!!! - Arthur Eirich

-1

我在这方面是个新手,但是我有自己的观点。如果你选择了一个特定的文件夹,并且想要从中提取最后一个文件。

     public static void main(String args[])  {
    //choose a FOLDER
    File  folderX = new File("/home/andy/Downloads");
    //extract all de files from that FOLDER
    File[] all_files_from_folderX = folderX.listFiles();
    System.out.println("all_files_from_folderXDirectories = " + 
                         Arrays.toString(all_files_from_folderX));
//we gonna need a new file
File a_simple_new_file = new File("");
// set to 0L (1JAN1970)
a_simple_new_file.setLastModified(0L);
 //check 1 by 1 if is bigger or no
for (File temp : all_files_from_folderX) {
if (temp.lastModified() > a_simple_new_file.lastModified())  {
            a_simple_new_file = temp; 
        }
//at the end the newest will be printed
System.out.println("a_simple_new_file = "+a_simple_new_file.getPath());
}
}}            

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接