我的内存中有各种文件,每个文件都以数字和格式结尾,例如:
/storage/emulated/0/packets
- 文件 1.x
- 文件 2.x
- ...
- 文件 11.x
我编写了一个代码来检索文件并按升序排序,但是当文件超过10个时,排序失败。
我的代码:
ArrayList<String> list;
public static boolean SetFileList(String directory){
list = new ArrayList<>();
if(DirectoryExist(directory)) { //DirectoryExist() verify if the parameter directory it's a true directory
File[] files = new File(directory).listFiles();
if (files == null) {
return false;
}
else if (files.length == 0) {
return false;
}
else {
Arrays.sort(files); //<------this method is supposed to sort
for (File file : files) {
list.add(file.getName());
}
return true;
}
}
else{
return false;
}
}
当我使用以下代码显示文件时:
for(int i = 0; i < list.size(); i++){
Log.i("File", list.get(i));
}
抛出类似的东西:
File: File 1.x
File: File 10.x
File: File 11.x
File: File 12.x
File: File 2.x
File: File 3.x
File: ...
但我想展示:
File: File 1.x
File: File 2.x
File: File 3.x
File: ...
File: File 10.x
File: File 11.x
File: File 12.x
为什么会发生这种情况?
最佳答案
我添加了一种方法,并且还使用了比较方法来对文件名进行排序。
public boolean SetFileList(String directory){
list = new ArrayList<>();
if(DirectoryExist(directory)) { //DirectoryExist() verify if the parameter directory it's a true directory
File[] files = new File(Environment.getExternalStorageDirectory() +"/"+directory).listFiles();
if (files == null) {
return false;
}
else if (files.length == 0) {
return false;
}
else {
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File file, File t1) {
int n1 = extractNumber(file.getName());
int n2 = extractNumber(t1.getName());
return n1 - n2;
}
private int extractNumber(String name) {
int i = 0;
try {
int s = name.indexOf(' ')+1;
int e = name.lastIndexOf('.');
String number = name.substring(s, e);
i = Integer.parseInt(number);
} catch(Exception e) {
i = 0; // if filename does not match the format
// then default to 0
}
return i;
}
}); //<------this method is supposed to sort
for (File file : files) {
list.add(file.getName());
System.out.println(file.getName());
}
return true;
}
}
else{
return false;
}
}
关于java - 按最后一个数字升序对文件数组进行排序的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48859858/