题目:读取当前项目根目录下所有后缀为.obj的文件,将这些Emp对象读取出来并存入到一个List集合中,然后按照员工工资从多到少的顺序依次输出员工信息
核心代码:
package homework10.homework1011;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
public class Demo004 {
public static void main(String[] args) {
try {
enterMain();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void enterMain() throws Exception{
Demo004 demo = new Demo004();
File file = new File(".");
List<Emp> list = demo.f1(file);
Collections.sort(list,new Comparator<Emp>(){
public int compare(Emp e1,Emp e2){
return e2.getSalary()-e1.getSalary();
}
});
for(Emp p:list){
System.out.println(p);
}
}
public List<Emp> f1(File file) throws Exception{
List<Emp> list = new ArrayList<Emp>();
File[] f = file.listFiles(new FileFilter(){
public boolean accept(File dir) {
return dir.getName().endsWith(".obj");
}
});
for(File f0:f){
list.add(f2(f0));
}
return list;
}
public Emp f2(File file) throws Exception{
RandomAccessFile raf = new RandomAccessFile(file,"r");
byte[] bytes = new byte[(int)file.length()];
int i = raf.read(bytes);
String str = new String(bytes,0,i);
String[] str0 = str.split(",");
String name = str0[0];
int age = Integer.parseInt(str0[1]);
String gender = str0[2];
int salary = Integer.parseInt(str0[3]);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date hiredate = sdf.parse(str0[4]);
Emp emp = new Emp(name,age,gender,salary,hiredate);
return emp;
}
}
class Emp{
private String name;
private int age;
private String gender;
private int salary;
private Date hiredate;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
public Emp() {
super();
}
public Emp(String name, int age, String gender, int salary, Date hiredate) {
super();
this.name = name;
this.age = age;
this.gender = gender;
this.salary = salary;
this.hiredate = hiredate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
@Override
public String toString() {
return "姓名:" + name + ", 年龄:" + age + ", 性别:" + gender + ", 薪资:" + salary + ", 入职时间:"
+ sdf.format(hiredate);
}
}
程序运行截图: