public static void main(String[] args) {
new SortFile().doWork()
}
private static final String FILE = "data.txt" // !!!modify
class Course implements Comparable<Course> {
String name
String teacher
int period
int price
Course(String name, String teacher, int period, int price) {
this.name = name
this.teacher = teacher
this.period = period
this.price = price
}
@Override
public int compareTo(Course target) {
if (price == target.price) {
return target.period - period
}
return target.price - price
}
@Override
public String toString() {
return "[NAME: " + name + " , TEACHER: " + teacher + " , PERIOD: " + period + " , PRICE: " + price + "]"
}
}
private void doWork() {
List<Course> courses = new ArrayList<Course>()
readFile(courses)
Collections.sort(courses)
int max = courses.size() >= 3 ? 3 : courses.size()
for (int i = 0 i < max i++) {
System.out.println(courses.get(i).toString())
}
}
private void readFile(List<Course> courses) {
try {
BufferedReader br = new BufferedReader(new FileReader(FILE))
String line = null
while ((line = br.readLine()) != null) {
String[] data = line.split(" ")
try {
data[3] = data[3].substring(0, data[3].length() - 1) // delete 元
Course course = new Course(data[0], data[1], Integer.parseInt(data[2]), Integer.parseInt(data[3]))
courses.add(course)
} catch (Exception e) {}
}
br.close()
} catch (IOException e) {
e.printStackTrace()
}
}
}
亲,建议你这样,一行一行的读取,全部读取完,每一行数据放入一个List<String>中,然后使用Collections.sort(T extends List<T>)一下就排好序了。方便快捷
有什么问题你都可以追问我,没问题望采纳,谢谢!
参数里面的isAscend 用来决定是升序排列 还是降序排列:/***
* 按最后修改时间排序
* @param list
* @param isAscend
*/
public static void sortListByTime(List<FileInfo>list , boolean isAscend) {
// 对ListView中数据list排序
ComparatorByTime comparator = new ComparatorByTime(isAscend)
if (!list.isEmpty()) {
Log.e("sortListByTime()", "")
synchronized (list) {
Collections.sort(list, comparator)
}
}
}
/**
* 按文件大小排序
* @param list
*/
public static void sortListBySize(List<FileInfo>list , boolean isAscend) {
// 对ListView中数据list排序
ComparatorBySize comparator = new ComparatorBySize(isAscend)
if (!list.isEmpty()) {
Log.e("sortListBySize()", "")
synchronized (list) {
Collections.sort(list, comparator)
}
}
}
/**
* 按文件名称排序
* @param list
*/
public static void sortListByName(List<FileInfo>list , boolean isAscend) {
// 对ListView中数据list排序
ComparatorByName comparator = new ComparatorByName(isAscend)
if (!list.isEmpty()) {
Log.e("sortListByName()", "")
synchronized (list) {
Collections.sort(list, comparator)
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)