java 如何使用Java从目录中仅获取10个最后修改的文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5005965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:01:39  来源:igfitidea点击:

How to get only 10 last modified files from directory using Java?

java

提问by user618111

i'm beginner and i found an old thread about lastmodified files in java. What i want is to get only 10 recent files from a directory and move them to another directory.

我是初学者,我发现了一个关于 java 中 lastmodified 文件的旧线程。我想要的是从一个目录中只获取 10 个最近的文件并将它们移动到另一个目录。

This code found in this forum is working well but it gets all files from a directory and sort them with date.

在此论坛中找到的这段代码运行良好,但它从目录中获取所有文件并按日期对它们进行排序。

Any help will be aprreciated, thank you

任何帮助将不胜感激,谢谢

Here is the code:

这是代码:

import java.io.File;
import java.util.Arrays;
import java.util.Comparator;


public class Newest {
    public static void main(String[] args) {
        File dir = new File("C:\your\dir");
        File [] files  = dir.listFiles();
        Arrays.sort(files, new Comparator(){
            public int compare(Object o1, Object o2) {
                return compare( (File)o1, (File)o2);
            }
            private int compare( File f1, File f2){
                long result = f2.lastModified() - f1.lastModified();
                if( result > 0 ){
                    return 1;
                } else if( result < 0 ){
                    return -1;
                } else {
                    return 0;
                }
            }
        });
        System.out.println( Arrays.asList(files ));
    }
}


i'm beginner here sorry if made some mistakes using the forum.

我是初学者,如果在使用论坛时犯了一些错误,请见谅。

so for me i don't know how to insert the above in a new code.

所以对我来说,我不知道如何在新代码中插入上述内容。

And if i keep the first code, i would like to store the 10 recents files into another folder, i trie this but it puts all files in the directory.

如果我保留第一个代码,我想将 10 个最近的文件存储到另一个文件夹中,我尝试这样做,但它将所有文件放在目录中。

any help please

任何帮助请

Thank you

谢谢

import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
import java.io.*;
import java.text.*;
import java.util.*;




    public class Newest
    {
        public static void main(String[] args)
        {
            File dir = new File("c:\File");
            File[] files = dir.listFiles();
            Arrays.sort(files, new Comparator<File>()
            {
                public int compare(File f1, File f2)
                {
                    return Long.valueOf(f2.lastModified()).compareTo
                            (
                            f1.lastModified());
                }
            });
            //System.out.println(Arrays.asList(files));
            for(int i=0, length=Math.min(files.length, 12); i<length; i++) {
        System.out.println(files[i]);


    for (File f : files) {
            System.out.println(f.getName() + " " + sdf.format(new Date(f.lastModified())));
            File dir = new File("c://Target");
            boolean success = f.renameTo(new File(dir,f.getName()));
            if (!success)


            }
        }
    } 

回答by Asaph

In your code example, change:

在您的代码示例中,更改:

System.out.println( Arrays.asList(files ));

to:

到:

for(int i=0, length=Math.min(files.length, 10); i<length; i++) {
    System.out.println(files[i]);
}

回答by rahulmohan

Getting all the files and then sorting it is the only 'correct' way as per the specifications. But here is another approach which is a hack that uses the FileFilter as a visitor and does an on the fly insertion sort. On my machine the performance was about 4 times better on a directory with 2300 files (an image directory)

获取所有文件然后对其进行排序是按照规范唯一“正确”的方式。但这是另一种方法,它是一种 hack,它使用 FileFilter 作为访问者并进行动态插入排序。在我的机器上,具有 2300 个文件的目录(一个图像目录)的性能大约提高了 4 倍

private File[] getTopFiles() {
    File dir = new File("C:\icons_svr");
    SortFilter filter = new SortFilter(10);
    dir.listFiles(filter);      
    File[] topFiles = new File[10];
    return filter.topFiles.toArray(topFiles);
}

Code for InsertionSortFilter:

InsertionSortFilter 的代码:

    class SortFilter implements FileFilter {

        final LinkedList<File> topFiles;
        private final int n;

        public SortFilter(int n) {
            this.n = n;
            topFiles = new LinkedList<File>();
        }

        public boolean accept(File newF) {
            long newT = newF.lastModified();

            if(topFiles.size()==0){
                //list is empty, so we can add this one for sure
                topFiles.add(newF);
            } else {
                int limit = topFiles.size()<n?topFiles.size():n;
                //find a place to insert
                int i=0;
                while(i<limit && newT <= topFiles.get(i).lastModified())
                    i++;

                if(i<limit){    //found
                    topFiles.add(i, newF);
                    if(topFiles.size()>n) //more than limit, so discard the last one. Maintain list at size n
                        topFiles.removeLast(); 
                }
            }
            return false;
        }

    }

回答by Edwin Buck

The operating system doesn't take a sorting routine in asking for files. As a result, the only solution is to grab all files (to ensure that you don't skip over one of the ones you want) and to sort them yourself.

操作系统在请求文件时不采用排序例程。因此,唯一的解决方案是获取所有文件(以确保您不会跳过您想要的文件之一)并自行对它们进行排序。

File systems do typically provide routines to grab files based on their file name, and Java exposes this through a list(...)which takes a FileFilterparameter.

文件系统通常会提供根据文件名抓取文件的例程,Java 通过list(...)带有FileFilter参数的a 公开这一点。

In Java 1.7 (whenever they release it), there are new File oriented facilities which will allow you access to an abstraction of the underlying file system. With such facilities, one could conceivable create a file visitor, but that won't help the situation much, as you have no idea which files you may skip without actually looking at it's modification time. This means that even with a visiting interface, you'll still have to check the modification time of every file to make sure you didn't miss one of the ten files you wanted.

在 Java 1.7(无论何时发布)中,都有新的面向文件的工具,允许您访问底层文件系统的抽象。使用这样的工具,可以想象创建一个文件访问者,但这对情况没有多大帮助,因为您不知道可以跳过哪些文件而不实际查看它的修改时间。这意味着即使有访问界面,您仍然必须检查每个文件的修改时间,以确保您没有错过您想要的十个文件之一。