Java I/O读取和解析.emp文件示例
1.使用到的知识点
IO流
存数据和读数据
集合
用来存储解析的数据,对数据进行相关操作
文件操作
创建相关的文件存储数据
2.示例1
2.1存储几个员工数据到不同的文件
2.1.1题目要求
要求用户输入一个员工信息,格式为:
name,age,gender,salary,hiredate
例如:
张三,25,男,5000,2006-02-15
然后将输入的员工信息解析成Emp对象。
然后将该Emp对象的toString返回的字符串写入到文件中,该文件的
名字为:name.emp,以上面的例子,那么该文件名为:张三.emp
至少运行5次该程序,输入五个员工信息,并生成5个文件。
2.1.2相关代码
public class Exercise15 {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("输入员工信息:");
String message = scanner.next();
Emp object = getObject(message);
System.out.println(object);
saveData(object);
}
//解析输入的员工对象信息
private static Emp getObject(String string) throws ParseException {
String[] str = string.split(",");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Emp emp = new Emp(str[0], Integer.parseInt(str[1]), str[2], Double.parseDouble(str[3]), sdf.parse(str[4]));
return emp;
}
//保存数据
private static void saveData(Emp emp) throws IOException {
String name = emp.getName();
File file = new File(name+".emp");
if (!file.exists()) {
file.createNewFile();
}
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(emp);
oos.close();
System.out.println("存入数据成功!");
}
}
class Emp implements Serializable {
private String name;
private int age;
private String gender;
private double salary;
private Date hireDate;
public Emp() {
}
public Emp(String name, int age, String gender, double salary, Date hireDate) {
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 double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Date getHireDate() {
return hireDate;
}
public void setHireDate(Date hireDate) {
this.hireDate = hireDate;
}
@Override
public String toString() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return name+","+age+","+name+","+salary+","+sdf.format(hireDate);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Emp emp = (Emp) o;
return age == emp.age &&
Double.compare(emp.salary, salary) == 0 &&
Objects.equals(name, emp.name) &&
Objects.equals(gender, emp.gender) &&
Objects.equals(hireDate, emp.hireDate);
}
@Override
public int hashCode() {
return Objects.hash(name, age, gender, salary, hireDate);
}
}
2.1.3结果展示
2.2读取存储数据的文件
2.2.1题目要求
编写一个程序,将当前目录下所有员工文件进行读取,并解析出所有员工为Emp
对象并存入集合。然后排序该集合,按照员工的年龄排序,年龄大的靠前,年龄小的靠后。排序完毕后输出结果。
2.2.2相关代码
public class Exercise16 {
public static void main(String[] args) throws Exception {
System.out.println("得到相关文件:");
File[] files = getFiles();
for (File file : files) {
System.out.println(file.getName());
}
System.out.println("读取数据并查看:");
List<Emp> list = readData(files);
for (Emp emp : list) {
System.out.println(emp);
}
System.out.println("根据年龄降序:");
sortData(list);
Iterator<Emp> i = list.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
//根据年龄排序
private static void sortData(List<Emp> list){
Collections.sort(list, (o1, o2) -> o2.getAge()-o1.getAge());
}
//得到存入数据的文件
private static File[] getFiles(){
File file = new File("./");
File[] files = file.listFiles(file1 -> file1.getName().endsWith(".emp"));
return files;
}
//读出数据存入到集合中
private static List<Emp> readData(File[] files) throws Exception {
List<Emp> list = new ArrayList<>();
ObjectInputStream ois = null;
for (File file : files) {
ois = new ObjectInputStream(new FileInputStream(file));
Object object=ois.readObject();
if (object instanceof Emp) {
Emp p = (Emp)object;
list.add(p);
}
}
ois.close();
System.out.println("读取成功!");
return list;
}
}
2.2.3结果展示
2.3获得入职20周年纪念日派对日期
文件获取:emp.dat文件
提取码: vf6a
复制这段内容后打开百度网盘手机App,操作更方便哦
2.3.1题目要求
编写一个程序,将当前目录下所有的员工文件进行读取,并解析出所有员工为Emp
对象并存入Map。其中key为该员工的名字,value为该员工的emp对象。
然后,要求用户输入一个员工名字,若该员工存在,则输出该员工的名字,年龄,工资,以及入职20周年的纪念日当周的周六的日期。
即:输入名字"张三"
若该员工存在,则输出如下格式:
张三,25,5000,2006-02-14
入职20周年纪念日派对日期: 2026-02-14 (注:若入职日期为:2006-02-14)
若该员工不存在,则输出:“查无此人”
2.3.2相关代码
public class Exercise17 {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws Exception {
File[] files = getFiles();
System.out.println("得到存入数据的文件名:");
for (File file : files) {
System.out.println(file.getName());
}
Map<String, Emp> data = getData(files);
System.out.println("遍历map中的数据:");
Set<Map.Entry<String, Emp>> entries = data.entrySet();
for (Map.Entry<String, Emp> entry : entries) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
// data.forEach((s, emp) -> System.out.println(s+":"+emp));
System.out.println("请输入一个员工的名字:");
String name = scanner.next();
getMessage(data, name);
}
//判断一个员工存在,存在并输出对应信息和入职纪念日
private static void getMessage(Map<String, Emp> map, String name) {
Set<String> set = map.keySet();
while(true){
if (!map.containsKey(name)) {
System.out.println("该员工不存在!");
System.out.println("请重新输入一个员工的名字:");
name = scanner.next();
continue;
}
Emp e = map.get(name);
System.out.println(name + ":" + e);
Date hireDate = e.getHireDate();
Calendar calendar = Calendar.getInstance();
calendar.setTime(hireDate);
calendar.add(Calendar.YEAR, 20);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
Date time = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String format = sdf.format(time);
System.out.println("员工入职20周年纪念日派对日期");
System.out.println(format);
break;
}
}
//读取存入员工信息的文件名
private static File[] getFiles() {
File file = new File("./");
File[] files = file.listFiles((file1) -> file1.getName().endsWith(".emp"));
return files;
}
//解析文件存到Emp对象中,在将对象存到Map中
private static Map<String, Emp> getData(File[] files) throws Exception {
HashMap<String, Emp> map = new HashMap<>();
ObjectInputStream ois = null;
for (File file : files) {
ois = new ObjectInputStream(new FileInputStream(file));
Object object = ois.readObject();
if (object instanceof Emp) {
Emp e = (Emp) object;
map.put(e.getName(), e);
}
}
return map;
}
}
2.3.4结果展示
3.示例2
3.1获取Emp.dat文件
3.2题目要求
将emp.dat文件中所有员工解析出来,并创建为若干Emp实例存入一个
集合,然后输出该集合中每个员工信息。
该文件800字节,每80个字节为一个员工的信息。
其中:
name为字符串,长度为32个字节,编码为:UTF-8
age为int,长度为4个字节
gender为字符串,长度为10个字节,编码为:UTF-8
salary为int,长度为4个字节
hiredate为字符串,格式"yyyy-MM-dd",长度为30个字节,编码为:UTF-8
格式可参考当前包中emp.jpg图
提示:
使用RandomAccessFile读取字符串时,例如name,可以先读取32个字节,再按照UTF-8
转换为字符串,读取age时可以直接使用readInt方法。依次类推。
3.2.1相关代码
public class Exercise18 {
public static void main(String[] args) throws Exception {
List<Emp1> data = getData(new File("emp.dat"));
showData(data);
}
//遍历集合中的数据
private static void showData(List<Emp1> list){
Iterator<Emp1> i = list.iterator();
while(i.hasNext()){
System.out.println(i.next());
}
// list.forEach(emp1 -> System.out.println(emp1));
}
//读取Emp.dat文件中的员工信息
private static List<Emp1> getData(File file) throws Exception {
List<Emp1> list = new LinkedList<>();
RandomAccessFile raf = new RandomAccessFile(file, "rw");
if (!file.exists()) {
return null;
}
for (int i = 0; i < 800/80; i++) {
int number = 80 *i;
raf.seek(number);
byte[] bs=new byte[Emp1.NAME];
String name = new String(bs,0,raf.read(bs));
raf.seek(number+Emp1.NAME);
int age = raf.readInt();
raf.seek(number+Emp1.NAME+Emp1.AGE);
byte[] bs1=new byte[Emp1.GENDER];
String gender=new String(bs1,0,raf.read(bs1));
raf.seek(number+Emp1.NAME+Emp1.AGE+Emp1.GENDER);
int salary = raf.readInt();
raf.seek(number+Emp1.NAME+Emp1.AGE+Emp1.GENDER+Emp1.SALARY);
byte[] bs2=new byte[Emp1.DATE];
String date=new String(bs2,0,raf.read(bs2));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date hireDate = sdf.parse(date);
Emp1 e = new Emp1(name, age, gender, salary, hireDate);
list.add(e);
}
return list;
}
}
class Emp1{
public static final int NAME=32;
public static final int AGE=4;
public static final int GENDER=10;
public static final int SALARY=4;
public static final int DATE=30;
private String name;
private int age;
private String gender;
private int salary;
private Date hireDate;
public Emp1() {
}
public Emp1(String name, int age, String gender, int salary, Date date) {
this.name = name;
this.age = age;
this.gender = gender;
this.salary = salary;
this.hireDate = date;
}
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() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return name+","+age+","+gender+","+salary+","+sdf.format(hireDate);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Emp1 emp1 = (Emp1) o;
return age == emp1.age &&
salary == emp1.salary &&
Objects.equals(name, emp1.name) &&
Objects.equals(gender, emp1.gender) &&
Objects.equals(hireDate, emp1.hireDate);
}
@Override
public int hashCode() {
return Objects.hash(name, age, gender, salary, hireDate);
}
}