java 读取当前项目根目录下所有后缀为obj的文件将这些Emp对象读取出来 并存入到一个List集合中然后按照员工工资从多到少的顺序依次输出员工信息
假设Emp对象的定义如下:
public class Emp {
private String name;
private int age;
private double salary;
public Emp(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
// getters and setters
}
可以使用如下代码读取当前项目根目录下所有后缀为.obj的文件:
List<Emp> empList = new ArrayList<>();
File dir = new File(".");
File[] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".obj");
}
});
for (File file : files) {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) {
Emp emp = (Emp) in.readObject();
empList.add(emp);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
然后可以使用如下代码按照员工工资从多到少的顺序输出员工信息:
Collections.sort(empList, new Comparator<Emp>() {
@Override
public int compare(Emp o1, Emp o2) {
return Double.compare(o2.getSalary(), o1.getSalary());
}
});
for (Emp emp : empList) {
System.out.println(emp.getName() + ", " + emp.getAge() + ", " + emp.getSalary());
}
``
原文地址: https://www.cveoy.top/t/topic/hdIk 著作权归作者所有。请勿转载和采集!