简体   繁体   English

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

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

i'm beginner and i found an old thread about lastmodified files in java. 我是初学者,我发现了一个关于java中lastmodified文件的旧线程。 What i want is to get only 10 recent files from a directory and move them to another directory. 我想要的是从目录中只获取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)


            }
        }
    } 

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

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. 但是这里有另一种方法,它使用FileFilter作为访问者并进行即时插入排序。 On my machine the performance was about 4 times better on a directory with 2300 files (an image directory) 在我的机器上,在具有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;
        }

    }

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 FileFilter parameter. 文件系统通常提供基于文件名来获取文件的例程,Java通过带有FileFilter参数的list(...)公开它。

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. 在Java 1.7中(每当它们发布它时),都有新的面向文件的工具,它们允许您访问底层文件系统的抽象。 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. 这意味着即使使用访问界面,您仍然需要检查每个文件的修改时间,以确保您没有错过您想要的十个文件中的一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 获取Java中目录中最近7天内修改的所有文件 - Get all files modified in last 7 days in a directory in Java 如何在java中获取目录的最后修改日期和时间 - How to get the last modified date and time of a directory in java 获取目录中文件的上次修改日期 - Get last Modified Date of Files in a directory 如何从文件列表中获取最后修改的文件 - How to get the last modified file from a list of files 如何使用Java在目录中仅保留最新的10个文件? - how can I leave only last 10 newest files in a dir using java? 如何获取当前目录列表的数组,包括Java中的文件/目录名称,最近修改的和大小? - How to get an array of current directory listing including file/directory name, last modified, and size in Java? 如何使用java获取第一个文件以及最后修改的文件 - How to get the first file and also the last modified file using java 使用 Java 从本地克隆的 Git 存储库中获取修改过的文件 - Get modified files from locally cloned Git repository using Java 在 Java 中获取最新(降序上次修改)n 个文件的最佳优化方法是什么 - 无需加载大目录的所有文件 - what is best optimized way in Java to get latest (Descending Last-Modified) n files - without loading all files of a large directory 如何使用 java 将文件从子目录获取到 ArrayList? - How to get files from sub-directory into ArrayList using java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM