I've got a method that returns to me a String[]
of names of the Files
of a current path, the thing I'm trying to do is make a method that returns to me this String[]
of names but sorted by date, and sorted by size, I've almost done this, but I'm missing something. I know to sort it's used Arrays.sort()
but the thing is that I don't know how to join all.
This is what I've got (No sorted)
File dir = new File(this.path);
File[] filelist = dir.listFiles();
String[] theNamesOfFiles;
if (filelist.length == 0) {
theNamesOfFiles = new String[1];
} else {
theNamesOfFiles = new String[filelist.length];
}
if (filelist.length == 0) {
theNamesOfFiles[0] = "This folder is empty";
} else {
for (int i = 0; i < theNamesOfFiles.length; i++) {
theNamesOfFiles[i] = filelist[i].getName();
}
}
return theNamesOfFiles;
Now I tried to do a SortByDate()
method but I don't know how to make to get those File[]
to make the previous method :
public File[] SortByDate(File test) {
final File[] sortedByDate = test.listFiles();
if (sortedByDate != null && sortedByDate.length > 1) {
Arrays.sort(sortedByDate, new Comparator < File > () {
@Override
public int compare(File object1, File object2) {
return (int)((object1.lastModified() > object2.lastModified()) ? object1.lastModified() : object2.lastModified());
}
});
return sortedByDate;
}
return sortedByDate;
}
And I think I know how to get the size of a File
doing :
Integer.parseInt(String.valueOf(filelist[i].length() / 1024))
Shall I do this also with the Compare<File>()
?
What I'm misunderstanding or missing?
EDIT
Now what I've tried is create a private File[] SortedByDate;
, and I've implemented this method :
public void SortByDate() {
File test = new File(this.path);
this.SortedByDate = test.listFiles();
if (this.SortedByDate != null && this.SortedByDate.length > 1) {
Arrays.sort(this.SortedByDate, new Comparator < File > () {
@Override
public int compare(File object1, File object2) {
return (int)((object1.lastModified() > object2.lastModified()) ? object1.lastModified() : object2.lastModified());
}
});
}
for (int i = 0; i < this.SortedByDate.length; i++) {
Log.d("SortedByDate", this.SortedByDate[i].getName());
}
}
And then I've created another method that looks like :
public String[] FilesFoundSortedByDate() {
SortByDate();
String[] theNamesOfFiles;
if (this.SortedByDate.length == 0) {
theNamesOfFiles = new String[1];
} else {
theNamesOfFiles = new String[this.SortedByDate.length];
}
if (this.SortedByDate.length == 0) {
theNamesOfFiles[0] = "This folder is empty";
} else {
for (int i = 0; i < theNamesOfFiles.length; i++) {
theNamesOfFiles[i] = this.SortedByDate[i].getName();
}
}
return theNamesOfFiles;
}
And I thought to call the function of SortByDate
and then use the File[] of the new attribute created, but it isn't sorting.