我从目录中获取所有文件,然后根据需要从中挑选文件并将它们存储在数组中,现在我想对最后修改过的文件进行排序。这是我正在使用的代码
public static int GetFilesCount(File folderPath,int count,String type,Context context)
{
BackupCount=count;
BackupFolderPath=folderPath;
Backuptype=type;
con=context;
DatabaseHandler objhandler;
Cursor cursor=null;
int total = 0;
String ext="";
// Check files count set by user
File[] fList = folderPath.listFiles();
ArrayList<String> myfiles = new ArrayList<String>();
for (File file : fList){
if (file.isFile()){
try {
String FileName=file.getName();
ext=GetFileExtension(FileName);
if(ext.equals("db"))
{
objhandler=new DatabaseHandler(context, folderPath+File.separator+FileName, null);
database= objhandler.openDataBase();
String selectQuery = "SELECT * FROM "+ type + " LIMIT 1";
cursor = database.rawQuery(selectQuery, null);
Integer ColCount=cursor.getColumnCount();
if(cursor.getCount()>0)
{
if(Backuptype.equals("SMS"))
{
if(ColCount.equals(9))
{
myfiles.add(FileName);
total++;
}
}
else if(Backuptype.equals("CallLogs"))
{
if(ColCount.equals(6))
{
myfiles.add(FileName);
total++;
}
}
else if(Backuptype.equals("Contacts"))
{
if(ColCount.equals(9))
{
myfiles.add(FileName);
total++;
}
}
}
if(total>count)
{
// String[] listFiles=new String[myfiles.size()];
// listFiles = myfiles.toArray(listFiles);
// File[] f = null;
for(int i=0;i<=myfiles.size();i++)
{
// f[i]=new File(folderPath+File.separator+myfiles.get(i));
System.out.println("Total SMS Files: "+myfiles.size());
System.out.println("file in folder: "+myfiles.get(i).toString());
}
/*Arrays.sort(f, new Comparator<File>(){
public int compare(File f1, File f2)
{
return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
} });*/
System.out.println("file in folder: "+myfiles.size());
// Deletefile(folderPath+File.separator+myfiles.get(0));
}
}
}catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}finally{
cursor.close();
database.close();
}
}
}
return 1;
}
答案 0 :(得分:1)
尝试将这部分代码合并到您的代码中:
final List<File> files = new ArrayList<File>();
Collections.sort(files, new Comparator<File>()
{
@Override
public int compare(final File o1, final File o2)
{
return o1.lastModified() >= o2.lastModified() ? 1 : -1;
}
});
答案 1 :(得分:0)
来自你的评论:
我很困惑如何将所选文件放入File []
因为你有:
// File[] f = null;
我认为这是你缺少的部分
File[] f = new File[myfiles.size()]; // init the array which should hold the files
for(int i = 0; i < myfiles.size(); i++) {
files[i] = new File(folderPath+File.separator+myfiles.get(i));
}
然后你可以使用Arrays.sort方法
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return Long.valueOf(o1.lastModified()).compareTo(o2.lastModified());
}
});
更好的是,您应该使用List并使用Collections.sort
List<File> f = new ArrayList<>();
for(int i = 0; i < myfiles.size(); i++) {
f.add(new File(folderPath+File.separator+myfiles.get(i)));
}
Collections.sort(f, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return Long.valueOf(o1.lastModified()).compareTo(o2.lastModified());
}
});