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

UDPATE

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

4

2 回答 2

9

Jimfs 使用 Java 7 文件 API。它并没有真正与旧FileAPI 混合,因为File对象总是绑定到默认文件系统。所以不要使用File.

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

Files.setLastModifiedTime(path, FileTime.fromMillis(millis));
于 2016-02-11T17:19:00.253 回答
-1

我是新手,但如果您选择 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());
}
}}            
于 2017-08-04T23:28:30.473 回答