I/O流综合练习题
(1)要编写一个dog.properties
name=tom
age=5
color=red
(2)编写Dog 类(name,age,color)创建一个dog对象,读取dog.properties 用相应的内容完
成属性初始化,并输出
(3)将创建的Dog 对象 ,序列化到 文件 dog.dat 文件
package chapter19.Properties;
import org.junit.Test;
import java.io.*;
import java.util.Properties;
/**
* @Author Java顶针
* @Version 1.0
*/
public class Homework {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Properties properties = new Properties();
properties.setProperty("name","TOM");
properties.setProperty("age","5");
properties.setProperty("color","red");
//写入信息到文件
properties.store(new FileOutputStream("src/dog.properties"),null);
System.out.println("写入成功");
//读取信息
BufferedReader brr = new BufferedReader(new FileReader("src/dog.properties"));
Dog dog = new Dog(properties.getProperty("name"), Integer.parseInt(properties.getProperty("age")), properties.getProperty("color"));
System.out.println("读取成功");
String decPath = "D:/javaTest/dog.dat";
ObjectOutputStream obj = new ObjectOutputStream(new FileOutputStream(decPath));
obj.writeObject(new Dog(dog.getName(), dog.getAge(), dog.getColor()));
obj.close();
brr.close();
}
@Test
public void readDog() throws IOException, ClassNotFoundException {//读取序列化对象
String decPath = "D:/javaTest/dog.dat";
ObjectInputStream obj = new ObjectInputStream(new FileInputStream(decPath));
Object o = obj.readObject();
Dog dog = (Dog) o;
System.out.println("读取成功:\n"+"name:"+dog.getName()+"\n"+"age:"+dog.getAge()+"\n"+"color:"+dog.getColor());
}
}
class Dog implements Serializable {
private String name;
private int age;
private String color;
public Dog(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
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 getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
", color='" + color + '\'' +
'}';
}
}