猿问

Java读取文件名并按升序存储

从特定目录读取文件并将所有文件名存储在数组列表中


File directory = new File(path);

        File[] listOfFiles = directory.listFiles();

        int fileCount = directory.list().length;

        List<String> files = new ArrayList<>();

        for (int i = 0; i < fileCount; i++) {

            String inputFilePath = path + listOfFiles[i].getName();

            String inputFileName = listOfFiles[i].getName();

            files.add(inputFileName);

        }

我期望按顺序(升序)存储文件,但实际是


1.jpg

10.jpg

11.jpg

12.jpg

13.jpg

14.jpg

15.jpg

16.jpg

17.jpg

18.jpg

19.jpg

2.jpg

20.jpg

21.jpg

22.jpg

3.jpg

4.jpg

5.jpg

6.jpg

7.jpg

8.jpg

9.jpg

让我知道如何按升序存储文件,例如 1,2,3,4,5....10,11....20,21...etc.,)


跃然一笑
浏览 269回答 3
3回答

梦里花落0921

您可以将Collections.sort()与自定义比较器一起使用,该比较器比较每个文件名的整数前缀,如下面的 ArrayList files:Collections.sort(files, new Comparator<String>() {&nbsp; &nbsp; public int compare(String s1, String s2) {&nbsp; &nbsp; &nbsp; &nbsp; int s1Num = Integer.valueOf(s1.split("[.jpg]")[0]);&nbsp; &nbsp; &nbsp; &nbsp; int s2Num = Integer.valueOf(s2.split("[.jpg]")[0]);&nbsp; &nbsp; &nbsp; &nbsp; if (s1Num == s2Num) { return 0; }&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; else if (s1Num <&nbsp; s2Num) { return -1; }&nbsp; &nbsp; &nbsp; &nbsp; else { return 1; }&nbsp; &nbsp; }});for (String file: files) {&nbsp; &nbsp; System.out.println(file);}输出:1.jpg2.jpg3.jpg4.jpg5.jpg6.jpg7.jpg8.jpg9.jpg10.jpg11.jpg12.jpg13.jpg14.jpg15.jpg16.jpg17.jpg18.jpg19.jpg20.jpg21.jpg22.jpg

蝴蝶刀刀

当然是这个顺序。这些文件不是按算术排序而是按字典排序。您必须重命名所有单个数字文件以包含前导零以实现您期望的顺序或编写自定义排序方法并将其应用于包含您的文件名的列表。
随时随地看视频慕课网APP

相关分类

Java
我要回答