Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 按日期和大小对数组排序(文件)_Java_Arrays_Sorting - Fatal编程技术网

Java 按日期和大小对数组排序(文件)

Java 按日期和大小对数组排序(文件),java,arrays,sorting,Java,Arrays,Sorting,我有一个方法,它可以返回当前路径文件名的字符串[],我要做的是创建一个方法,它可以返回名称的字符串[],但按日期排序,按大小排序,我几乎完成了这项工作,但我遗漏了一些东西。我知道排序,但我不知道如何把所有的数组都连接起来 这就是我所没有的 File dir = new File(this.path); File[] filelist = dir.listFiles(); String[] theNamesOfFiles; if (filelist.length == 0) {

我有一个方法,它可以返回当前路径文件名的字符串[],我要做的是创建一个方法,它可以返回名称的字符串[],但按日期排序,按大小排序,我几乎完成了这项工作,但我遗漏了一些东西。我知道排序,但我不知道如何把所有的数组都连接起来

这就是我所没有的

 File dir = new File(this.path);
 File[] filelist = dir.listFiles();
 String[] theNamesOfFiles;
 if (filelist.length == 0) {
     theNamesOfFiles = new String[1];
 } else {
     theNamesOfFiles = new String[filelist.length];
 }

 if (filelist.length == 0) {
     theNamesOfFiles[0] = "This folder is empty";
 } else {
     for (int i = 0; i < theNamesOfFiles.length; i++) {

         theNamesOfFiles[i] = filelist[i].getName();
     }
 }
 return theNamesOfFiles;
我想我知道如何通过以下方式获得文件的大小:

我是否也要用比较法来做这件事

我误解了什么或错过了什么

编辑 现在我尝试创建一个私有文件[]SortedByDate;,我已经实现了这个方法:

public void SortByDate() {

File test = new File(this.path);
this.SortedByDate = test.listFiles();

if (this.SortedByDate != null && this.SortedByDate.length > 1) {
    Arrays.sort(this.SortedByDate, new Comparator < File > () {
        @Override
        public int compare(File object1, File object2) {
            return (int)((object1.lastModified() > object2.lastModified()) ? object1.lastModified() : object2.lastModified());
        }
    });
}
for (int i = 0; i < this.SortedByDate.length; i++) {
    Log.d("SortedByDate", this.SortedByDate[i].getName());
}
}
然后我创建了另一个方法,看起来像:

public String[] FilesFoundSortedByDate() {
SortByDate();
String[] theNamesOfFiles;
if (this.SortedByDate.length == 0) {
    theNamesOfFiles = new String[1];
} else {
    theNamesOfFiles = new String[this.SortedByDate.length];
}

if (this.SortedByDate.length == 0) {
    theNamesOfFiles[0] = "This folder is empty";
} else {
    for (int i = 0; i < theNamesOfFiles.length; i++) {

        theNamesOfFiles[i] = this.SortedByDate[i].getName();
    }
}
return theNamesOfFiles;
}

我想调用SortByDate函数,然后使用创建的新属性的文件[],但它没有排序。

按日期升序和大小升序排序文件列表

 void SortByDateAndSize(File[] fileList) {
    Arrays.sort(fileList, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            int r = Long.compare(o1.lastModified(), o2.lastModified());
            if (r != 0)
                return r;
            return Long.compare(o1.length(), o2.length());
        }
    });
}

排序功能。根据需要修改它们。他们所做的只是利用值并比较方法调用。理解这一点的关键是可用的

根据需要将逻辑串在一起,形成排序函数,因为实际的排序要求有点混淆

 private void sortByName(File[] files){
     Arrays.sort(files, new Comparator<File>() {
        @Override
        public int compare(File t, File t1) {
            return t.getName().compareTo(t1.getName());
        }
    });
}

private void sortByDate(File[] files){
    Arrays.sort(files, new Comparator<File>() {
        @Override
        public int compare(File t, File t1) {
            return (int) (t.lastModified() - t1.lastModified());
        }
    });
}

private void sortBySize(File[] files){
     Arrays.sort(files, new Comparator<File>() {
        @Override
        public int compare(File t, File t1) {
            return (int) (t.length() - t1.length());
        }
    });
}

即使这篇文章已经有了一个绝对正确的答案,我也尝试在没有旧的JavaIO包的情况下做所有事情,只使用NIO特性来解决性能问题。所以这里是下降。我不知道它在Android中是否可用,但在Java8中是可用的。基于Peter Neyens解决方案中的内容。这个解决方案是基于我提出的另一个问题


我使用Java8流和Lamda特性创建了一个函数,该函数根据上次修改的时间和文件大小对目录中的文件进行排序

public static String[] getSortedFileNames(File directory) {
    return Arrays
        // get all the files from the directory
        .stream(directory.listFiles())
        // sorting them first by last modified time and then by length
        // the sorted function uses a comparator (like your Comparator<File>
        // or a function which compares two files
        .sorted((f1, f2) -> {
            // first compare the two files by last modified (newest files first => compare f2 with f1)
            final int compareModified = Long.compare(f2.lastModified(), f1.lastModified());
            return compareModified != 0 
                ? compareModified 
                : Long.compare(f2.length(), f1.length()); // the two files have the same last modified time,
                                                          // lets sort them by file size (biggest files first)
        })
        // get the name of the file
        .map(File::getName)
        // return the names from the sorted files in a String array
        .toArray(String[]::new);
}
仅使用nio文件API更新2

使用Files.getLastModifiedTime和Files.size比较路径。 当这些方法中的一个抛出IOException时,我必须抛出RuntimeException,因为这在Comparator的compare方法中也是不可能的


我用lambdas做了一个小演示

public static void main(String[] args) {

    File f = new File(System.getProperty("user.home") + "/temp");

    List<File> files = Arrays.asList(f.listFiles(((dir, name) -> !(new File(dir,name)).isDirectory())));

    System.out.println("****** Listing as received *********** ");
    files.forEach(file -> System.out.println(file.getName()));

    System.out.println("****** Listing sorted by length *********** ");
    files.sort((f1,f2) -> Long.compare(f1.length(),f2.length()));
    files.forEach(file -> System.out.println(
          String.format("%-30s length = %2d",file.getName(),file.length())));

    System.out.println("****** Listing sorted by date **************");
    files.sort((f1,f2) -> Long.compare(f1.lastModified(),f2.lastModified()));
    files.stream()
          .map(file -> String.format("%-30s date mod = %2$td-%2tm-%2$tY %2$tH:%2$tM:%2$ts",file.getName(), new Date(file.lastModified())))
          .collect(Collectors.toList()).forEach(System.out::println);
}
生成的输出

****** Listing as received *********** .DS_Store allclasses-frame.html allclasses-noframe.html alltext_awesome.test alltext_java8.test alltext_oldjava.text bigDbTesting.mv.db bigDbTesting.trace.db constant-values.html cx_d_entity_npn.txt default-centos-66-pmd1.box deprecated-list.html F_TXN_Refresh.SFS.kjb fakedata.mv.db faker.mv.db help-doc.html index.html jdk160_26.zip keepPass_v0.xml ldapinfo.txt overview-frame.html overview-summary.html overview-tree.html package-list script.js simpleDbToFileTest.txt simpleDbToFileTest2.txt stringIncrementer.jar stylesheet.css table.csv temp.sql those.enc.copy.properties those.enc.properties those.properties untitled text 4.txt untitled text.txt untitled text111.txt ****** Listing sorted by length *********** cx_d_entity_npn.txt length = 0 package-list length = 20 untitled text 4.txt length = 39 untitled text111.txt length = 132 simpleDbToFileTest.txt length = 180 ldapinfo.txt length = 295 untitled text.txt length = 695 script.js length = 827 overview-frame.html length = 850 those.enc.copy.properties length = 853 those.enc.properties length = 853 allclasses-noframe.html length = 1243 allclasses-frame.html length = 1343 temp.sql length = 1504 those.properties length = 1836 bigDbTesting.trace.db length = 2673 index.html length = 2863 simpleDbToFileTest2.txt length = 3201 deprecated-list.html length = 3514 constant-values.html length = 3564 overview-summary.html length = 4043 alltext_awesome.test length = 4546 alltext_java8.test length = 4546 alltext_oldjava.text length = 4546 overview-tree.html length = 4821 F_TXN_Refresh.SFS.kjb length = 7254 help-doc.html length = 8242 stringIncrementer.jar length = 12243 .DS_Store length = 12292 stylesheet.css length = 12808 keepPass_v0.xml length = 14810 faker.mv.db length = 28672 table.csv length = 47820 bigDbTesting.mv.db length = 212992 fakedata.mv.db length = 75051008 jdk160_26.zip length = 87253361 default-centos-66-pmd1.box length = 20131307999 ****** Listing sorted by date ************** jdk160_26.zip date mod = 04-04-2014 10:09:1396620572 simpleDbToFileTest2.txt date mod = 02-07-2014 14:07:1404324435 simpleDbToFileTest.txt date mod = 03-07-2014 08:05:1404389127 cx_d_entity_npn.txt date mod = 23-09-2014 15:39:1411501165 F_TXN_Refresh.SFS.kjb date mod = 23-09-2014 16:17:1411503474 keepPass_v0.xml date mod = 21-10-2014 16:48:1413924527 ldapinfo.txt date mod = 22-10-2014 10:39:1413988799 untitled text111.txt date mod = 08-12-2014 09:05:1418047503 default-centos-66-pmd1.box date mod = 03-02-2015 10:56:1422978975 untitled text 4.txt date mod = 06-02-2015 23:14:1423282475 untitled text.txt date mod = 06-02-2015 23:14:1423282475 stringIncrementer.jar date mod = 13-02-2015 18:19:1423869592 fakedata.mv.db date mod = 19-02-2015 08:31:1424352716 faker.mv.db date mod = 24-03-2015 14:49:1427222991 table.csv date mod = 30-04-2015 10:07:1430402823 bigDbTesting.mv.db date mod = 30-04-2015 10:33:1430404409 bigDbTesting.trace.db date mod = 30-04-2015 10:43:1430405015 .DS_Store date mod = 27-05-2015 09:28:1432733304 alltext_awesome.test date mod = 08-06-2015 08:51:1433767887 alltext_java8.test date mod = 08-06-2015 08:51:1433767887 alltext_oldjava.text date mod = 08-06-2015 08:51:1433767887 stylesheet.css date mod = 08-06-2015 10:24:1433773446 package-list date mod = 08-06-2015 10:25:1433773522 script.js date mod = 08-06-2015 10:25:1433773522 overview-frame.html date mod = 08-06-2015 10:25:1433773522 allclasses-noframe.html date mod = 08-06-2015 10:25:1433773522 allclasses-frame.html date mod = 08-06-2015 10:25:1433773522 index.html date mod = 08-06-2015 10:25:1433773522 deprecated-list.html date mod = 08-06-2015 10:25:1433773522 constant-values.html date mod = 08-06-2015 10:25:1433773522 overview-summary.html date mod = 08-06-2015 10:25:1433773522 overview-tree.html date mod = 08-06-2015 10:25:1433773522 help-doc.html date mod = 08-06-2015 10:25:1433773522 temp.sql date mod = 08-06-2015 15:21:1433791297 those.properties date mod = 11-06-2015 14:33:1434047622 those.enc.copy.properties date mod = 11-06-2015 15:38:1434051531 those.enc.properties date mod = 11-06-2015 15:49:1434052178 最简单的方法是:

import org.apache.commons.io
import java.util.Arrays;
然后

该库中提供的其他比较器:

复合电子计算器, DefaultFileComparator, DirectoryFileComparator, ExtensionFileComparator, 名称文件比较器, PathFileComparator,
SizeFileComparator。

您是否尝试过,但失败了?因为它看起来很好。是的,这看起来很好。请看我的编辑,伙计。比较应返回-1、0或1。在这种情况下,您总是返回一个lastModified的正值。所以我想说它不起作用。另外,这是多余的整数。parseIntString.valueOffilelist[I]。长度/1024您能解释一下吗?是的,但它只返回一个int,我怎样才能返回整个文件[]排序?它已排序到位。这就是array.sort的返回值无效的原因。传入的数组已排序。它不会创建新数组。在示例代码中,文件是一个引用。它指向内存中某处的文件[]。您只需使用引用即可对该内存进行操作。这就是Arrays.sort正在做的事情。它使用引用对传入的文件[]进行排序。这就是所谓的原地排序,你的意思是如果我做类似sortByDatethis.SortedByDate;此文件[]已全部就绪排序?这是另一种方式,祝贺您。@Peter代码不错,但您已经阅读了File.listFiles的JavaDoc了吗?有人提到,最好使用Files.newDirectoryStream来查找大规模目录的性能问题。@NwDX感谢您提供的提示。我在下面找到了使用DirectoryStream的文件。@peterneens-Hm,您的更新代码使用Path.toFile,因此可能存在下一个缺点。我认为代码更像这样,没有旧的io包,除了IOException:stream.sortedtimeSizeComparator.mapPath::getFileName.mapPath::toString.toArrayString[]::new@谢谢。我已经知道从路径返回到文件不是正确的方法,但我还不太熟悉NIOAPI。我已经更新了我的答案,只使用nio,但是nio函数可能会抛出IOException,这对流和比较器不好。@PeterNeyens是的,流和异常有点棘手。我也对这个问题提出了解决办法。但是说实话,我必须感谢你给我的建议:-所以,希望这将是具有nio特性的最快解决方案。
public static String[] sortFiles(File directory) throws IOException {
    return Files
        // get all the paths in the directory
        .list(directory.toPath())
        // turn paths into files
        .map(Path::toFile)
        // sortying them first by last modfied and then by length
        .sorted((f1, f2) -> {
            // the sorted function uses a comparotor or a function which compares two files
            // first compare the two files by last modified (newest files first => * -1)
            final int compareModified = Long.compare(f2.lastModified(), f1.lastModified());
            return compareModified != 0 
                ? compareModified 
                : Long.compare(f2.length(), f1.length()); // the two files have the same last modified time,
                                                          // lets sort them by file size (biggist first)
        })
        // get the name of the file
        .map(File::getName)
        // return the names from the sorted files in a String array
        .toArray(String[]::new);
}
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

// run : sortFiles(Paths.get("/foo/bar/"))
public static String[] sortFiles(Path directory) throws IOException {
    return Files
        .list(directory)
        .sorted((p1, p2) -> {
            try {
                final int compareModified = Files.getLastModifiedTime(p2).compareTo(Files.getLastModifiedTime(p1));
                return compareModified != 0
                    ? compareModified
                    : Long.compare(Files.size(p2), Files.size(p1));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        })
        .map(Path::getFileName)
        .map(Path::toString)
        .toArray(String[]::new);
}
public static void main(String[] args) {

    File f = new File(System.getProperty("user.home") + "/temp");

    List<File> files = Arrays.asList(f.listFiles(((dir, name) -> !(new File(dir,name)).isDirectory())));

    System.out.println("****** Listing as received *********** ");
    files.forEach(file -> System.out.println(file.getName()));

    System.out.println("****** Listing sorted by length *********** ");
    files.sort((f1,f2) -> Long.compare(f1.length(),f2.length()));
    files.forEach(file -> System.out.println(
          String.format("%-30s length = %2d",file.getName(),file.length())));

    System.out.println("****** Listing sorted by date **************");
    files.sort((f1,f2) -> Long.compare(f1.lastModified(),f2.lastModified()));
    files.stream()
          .map(file -> String.format("%-30s date mod = %2$td-%2tm-%2$tY %2$tH:%2$tM:%2$ts",file.getName(), new Date(file.lastModified())))
          .collect(Collectors.toList()).forEach(System.out::println);
}
****** Listing as received *********** .DS_Store allclasses-frame.html allclasses-noframe.html alltext_awesome.test alltext_java8.test alltext_oldjava.text bigDbTesting.mv.db bigDbTesting.trace.db constant-values.html cx_d_entity_npn.txt default-centos-66-pmd1.box deprecated-list.html F_TXN_Refresh.SFS.kjb fakedata.mv.db faker.mv.db help-doc.html index.html jdk160_26.zip keepPass_v0.xml ldapinfo.txt overview-frame.html overview-summary.html overview-tree.html package-list script.js simpleDbToFileTest.txt simpleDbToFileTest2.txt stringIncrementer.jar stylesheet.css table.csv temp.sql those.enc.copy.properties those.enc.properties those.properties untitled text 4.txt untitled text.txt untitled text111.txt ****** Listing sorted by length *********** cx_d_entity_npn.txt length = 0 package-list length = 20 untitled text 4.txt length = 39 untitled text111.txt length = 132 simpleDbToFileTest.txt length = 180 ldapinfo.txt length = 295 untitled text.txt length = 695 script.js length = 827 overview-frame.html length = 850 those.enc.copy.properties length = 853 those.enc.properties length = 853 allclasses-noframe.html length = 1243 allclasses-frame.html length = 1343 temp.sql length = 1504 those.properties length = 1836 bigDbTesting.trace.db length = 2673 index.html length = 2863 simpleDbToFileTest2.txt length = 3201 deprecated-list.html length = 3514 constant-values.html length = 3564 overview-summary.html length = 4043 alltext_awesome.test length = 4546 alltext_java8.test length = 4546 alltext_oldjava.text length = 4546 overview-tree.html length = 4821 F_TXN_Refresh.SFS.kjb length = 7254 help-doc.html length = 8242 stringIncrementer.jar length = 12243 .DS_Store length = 12292 stylesheet.css length = 12808 keepPass_v0.xml length = 14810 faker.mv.db length = 28672 table.csv length = 47820 bigDbTesting.mv.db length = 212992 fakedata.mv.db length = 75051008 jdk160_26.zip length = 87253361 default-centos-66-pmd1.box length = 20131307999 ****** Listing sorted by date ************** jdk160_26.zip date mod = 04-04-2014 10:09:1396620572 simpleDbToFileTest2.txt date mod = 02-07-2014 14:07:1404324435 simpleDbToFileTest.txt date mod = 03-07-2014 08:05:1404389127 cx_d_entity_npn.txt date mod = 23-09-2014 15:39:1411501165 F_TXN_Refresh.SFS.kjb date mod = 23-09-2014 16:17:1411503474 keepPass_v0.xml date mod = 21-10-2014 16:48:1413924527 ldapinfo.txt date mod = 22-10-2014 10:39:1413988799 untitled text111.txt date mod = 08-12-2014 09:05:1418047503 default-centos-66-pmd1.box date mod = 03-02-2015 10:56:1422978975 untitled text 4.txt date mod = 06-02-2015 23:14:1423282475 untitled text.txt date mod = 06-02-2015 23:14:1423282475 stringIncrementer.jar date mod = 13-02-2015 18:19:1423869592 fakedata.mv.db date mod = 19-02-2015 08:31:1424352716 faker.mv.db date mod = 24-03-2015 14:49:1427222991 table.csv date mod = 30-04-2015 10:07:1430402823 bigDbTesting.mv.db date mod = 30-04-2015 10:33:1430404409 bigDbTesting.trace.db date mod = 30-04-2015 10:43:1430405015 .DS_Store date mod = 27-05-2015 09:28:1432733304 alltext_awesome.test date mod = 08-06-2015 08:51:1433767887 alltext_java8.test date mod = 08-06-2015 08:51:1433767887 alltext_oldjava.text date mod = 08-06-2015 08:51:1433767887 stylesheet.css date mod = 08-06-2015 10:24:1433773446 package-list date mod = 08-06-2015 10:25:1433773522 script.js date mod = 08-06-2015 10:25:1433773522 overview-frame.html date mod = 08-06-2015 10:25:1433773522 allclasses-noframe.html date mod = 08-06-2015 10:25:1433773522 allclasses-frame.html date mod = 08-06-2015 10:25:1433773522 index.html date mod = 08-06-2015 10:25:1433773522 deprecated-list.html date mod = 08-06-2015 10:25:1433773522 constant-values.html date mod = 08-06-2015 10:25:1433773522 overview-summary.html date mod = 08-06-2015 10:25:1433773522 overview-tree.html date mod = 08-06-2015 10:25:1433773522 help-doc.html date mod = 08-06-2015 10:25:1433773522 temp.sql date mod = 08-06-2015 15:21:1433791297 those.properties date mod = 11-06-2015 14:33:1434047622 those.enc.copy.properties date mod = 11-06-2015 15:38:1434051531 those.enc.properties date mod = 11-06-2015 15:49:1434052178
import org.apache.commons.io
import java.util.Arrays;
File directory = new File(".");
File[] files = directory.listFiles((FileFilter) FileFileFilter.FILE);
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);