按asc順序對文件進行排序我正在從目錄中獲取所有文件,然後根據需要從中選擇文件並將它們存儲在數組中,現在我想對最後修改的最後一個文件進行排序。下面是我使用如何根據最後修改
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;
}
http:// stackoverflo w.com/questions/203030/best-way-to-list-files-in-java-sorted-by-date-modified – Slartibartfast
有沒有必要張貼這麼多的代碼。唯一有趣的位被埋在底部(當您嘗試分類時,評論部分)。請解釋爲什麼這不適合你 - 你有錯誤嗎? –
@DuncanJones Array.sort()接受文件數組參數和比較對象我很困惑如何將選定的文件放入文件[] – Supreet