How to make a file browser with different sort display method.
We can get the file structure first and store in a list.
Then use Comparator interface to do different sort.
1. Suppose you have a class "MYFile" and need to sort the ArrayList of MyFiles
private List myFiles=new ArrayList();
2. Create a Class implements Comparator and with the compare method
class DirFirstComparator implements Comparator {
public int compare(MYFile emp1, MYFile emp2) {
MYFile myfile1 = (MYFile)emp1;
MYFile myfile2 = (MYFile)emp2;
if( myfile1.bdir){ // myfile1 is a directory
if( myfile2.bdir)
return ( myfile1.showname.compareToIgnoreCase(myfile2.showname));
else
return -1;
} else { // myfile1 is a file
if( myfile2.bdir )
return 1;
else
return ( myfile1.showname.compareToIgnoreCase(myfile2.showname));
}
}
3. Construct the Comparator and call Collections.sort( )
Comparator comparator = new DirFirstComparator( ); Collections.sort( myFiles, comparator );