一、在properties文件中手动写上姓名和年龄,读取到集合中,将该数据封装成学生对象,写到本地文件。
PropertiesUtils
package com.home;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesUtils {
private static PropertiesUtils proUtils;
private Properties p;
public PropertiesUtils() {
try {
p = new Properties();
p.load(new FileInputStream("admin.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static PropertiesUtils getInstance() {
if (proUtils == null) {
proUtils = new PropertiesUtils();
}
return proUtils;
}
public String getValur(String key) {
return p.getProperty(key);
}
}
Student
package com.home;
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Test01
package com.home;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Test01 {
public static void main(String[] args) throws IOException {
String name = PropertiesUtils.getInstance().getValur("name");
String age = PropertiesUtils.getInstance().getValur("age");
Student stu = new Student();
stu.setName(name);
stu.setAge(Integer.parseInt(age));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("1.txt"));
oos.writeObject(stu);
oos.close();
}
}