-1

i am fetching all the files from a directory and then picking the files according to need from them and storing them in an array now i want to sort that files with last modified last. Here is the code i am using

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;
}
beatgammit
  • 19,817
  • 19
  • 86
  • 129
Supreet
  • 2,451
  • 8
  • 25
  • 42
  • 1
    http://stackoverflow.com/questions/203030/best-way-to-list-files-in-java-sorted-by-date-modified – Vrashabh Irde Jul 11 '13 at 07:10
  • There is no need to post so much code. The only interesting bit is buried at the bottom (the commented section when you attempt to sort). Please explain why this hasn't worked for you - did you get an error? – Duncan Jones Jul 11 '13 at 07:11
  • @DuncanJones Array.sort() accept File array param and comparator object i am confused how to put selected file in File[] – Supreet Jul 11 '13 at 07:14
  • you should use File[] fList – Blackbelt Jul 11 '13 at 07:15
  • You could change `myfiles` to be a `List` and then use `Collections.sort()`. – Duncan Jones Jul 11 '13 at 07:19
  • @DuncanJones i have used that but it will not sort it with modified date it will sort it by name – Supreet Jul 11 '13 at 07:20
  • sort(List list, Comparator super T> c) can accept 2 agruments, so for the second argument, you should write implements a Comparator to do the compare thing. – OQJF Jul 11 '13 at 07:27

2 Answers2

1

Try combine this part of code into your code:

 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;
      }

    });
OQJF
  • 1,350
  • 9
  • 12
0

From your comment:

i am confused how to put selected file in File[]

and since you have:

// File[] f = null;

I think this is the part you are missing

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));
}

then you ca use the Arrays.sort method

Arrays.sort(files, new Comparator<File>() {
    @Override
    public int compare(File o1, File o2) {
        return Long.valueOf(o1.lastModified()).compareTo(o2.lastModified());
    }
});

Better yet, you should work with List and use 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());
    }
});
A4L
  • 17,353
  • 6
  • 49
  • 70
  • i think you have missed something here "List f = new ArrayList<>();" – Supreet Jul 11 '13 at 08:09
  • @Supreet If you are using java 1.6 or lower then you have to write `List f = new ArrayList();` for java 1.7 `List f = new ArrayList<>();` is correct. Is that what you mean? – A4L Jul 11 '13 at 08:13
  • i have implemented the snippet but this is not sorting the files – Supreet Jul 11 '13 at 08:34
  • @Supreet this should work actually, where in you your code you find out that the fiels are not sorted? do print them immediatly after the sort call or somewhere else? as far as i can see the method you have returns only an `int`. Can you edit your question an put in the relevant code snipets? – A4L Jul 11 '13 at 09:39