按字母顺序从目录中读取Android文件

时间:2018-01-01 16:34:05

标签: java android

我想按字母顺序处理Android文件。我已经在PC上用Java测试了它,它按字母顺序对文件进行了排序。但是,当我在Android中测试它时,我发现Android按大小读取文件。

你能帮我找到一种可以按字母顺序阅读Android文件的方法吗?

Android代码:

String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + "testface" + File.separator;
Log.d("MyTag", path);

File folder = new File(path);
File[] listOfFiles = folder.listFiles();

Arrays.sort(listOfFiles);

Log.d("MyTag", "no.of files: " + listOfFiles.length);

long startTime2 = System.nanoTime();
for (int i = 0; i < listOfFiles.length; i++) {
    if (listOfFiles[i].isFile()) {
        String filepath = path + listOfFiles[i].getName();
        Log.d("MyTag", "appface_image_filepath: " + filepath);
    }
}

调试日志:

01-01 22:09:11.042 8484-8484/com.example.nasif.facedetectionloop D/MyTag: /storage/emulated/0/DCIM/testface/
01-01 22:09:11.043 8484-8484/com.example.nasif.facedetectionloop D/MyTag: no.of files: 10
01-01 22:09:11.044 8484-8484/com.example.nasif.facedetectionloop D/MyTag: appface_image_filepath: /storage/emulated/0/DCIM/testface/11.jpg
01-01 22:09:11.044 8484-8484/com.example.nasif.facedetectionloop D/MyTag: appface_image_filepath: /storage/emulated/0/DCIM/testface/12.jpg
01-01 22:09:11.044 8484-8484/com.example.nasif.facedetectionloop D/MyTag: appface_image_filepath: /storage/emulated/0/DCIM/testface/17.jpg
01-01 22:09:11.044 8484-8484/com.example.nasif.facedetectionloop D/MyTag: appface_image_filepath: /storage/emulated/0/DCIM/testface/18.jpg
01-01 22:09:11.044 8484-8484/com.example.nasif.facedetectionloop D/MyTag: appface_image_filepath: /storage/emulated/0/DCIM/testface/19.jpg
01-01 22:09:11.045 8484-8484/com.example.nasif.facedetectionloop D/MyTag: appface_image_filepath: /storage/emulated/0/DCIM/testface/20.jpg
01-01 22:09:11.045 8484-8484/com.example.nasif.facedetectionloop D/MyTag: appface_image_filepath: /storage/emulated/0/DCIM/testface/27.jpg
01-01 22:09:11.045 8484-8484/com.example.nasif.facedetectionloop D/MyTag: appface_image_filepath: /storage/emulated/0/DCIM/testface/28.jpg
01-01 22:09:11.046 8484-8484/com.example.nasif.facedetectionloop D/MyTag: appface_image_filepath: /storage/emulated/0/DCIM/testface/3.jpg
01-01 22:09:11.046 8484-8484/com.example.nasif.facedetectionloop D/MyTag: appface_image_filepath: /storage/emulated/0/DCIM/testface/4.jpg

1 个答案:

答案 0 :(得分:1)

您可以实施自己的Comparator

Arrays.sort(listOfFiles, new Comparator<File>() {
    @Override
    public int compare(File f1, File f2) {
        return f1.getName().compareTo(f2.getName());
    }
});

如果你想要你的文件是1.jpg,2.jpg ... 10.jpg ...那么你可以先比较文件名的长度。

Arrays.sort(listOfFiles, new Comparator<File>() {
    @Override
    public int compare(File f1, File f2) {
        String name1 = f1.getName();
        String name2 = f2.getName();
        if (name1.length() == name2.length())
            return f1.getName().compareTo(f2.getName());
        return name1.length() - name2.length();
    }
});
相关问题