栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

IO流 使用properties 类读取配置文件,构建文件,序列化和反序列化

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

IO流 使用properties 类读取配置文件,构建文件,序列化和反序列化

使用properties 类读取配置文件,构建文件,序列化和反序列化 3.编程题 (1)要编写一个dog.properties name=tom r age=5 color=red (2)编写Dog类(name,age,color)创建一个dog对象,读取dog.properties用相应的内容完成属性初始化,并输出 (3)将创建的Dog对象,序列化到文件 dog.dat文件 (4)反序列化

dog.properties

name=tom
age=5
color=red
public class Homework03{
	public static void main(string[] args) throws IOException {
		
		String filePath = "src\dog.properties";
		Properties properties = new Properties();
		properties.load(new FildReader(filePath));
		String name = properties.get("name") + "";//Object -> String
		int age = Integer.parseInt(properties.get("age") + "");//Object -> int
		String color = properties.get("color") + "";//Object -> String

		new dog = new Dog(name, age, color);
		System.out.println("===dog对象信息===");
		System.out.println(dog);

		//序列化
		String serFilePath = "e:\dog.dat";
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(serFilePath));
		oos.writeObject(dog);
		//关闭流
		oos.close();
		System.out.println("dog对象序列化完成..");
	}
	
	//(4)反序列化
	//在编写一个方法,反序列化dog
	public void m1(){
		String serFilePath = "e:\dog.dat";
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(serFilePath ));
		Dog dog = (Dog) ois.readObject();
		
		System.out.println("===反序列化后 dog===");
		System.out.println(dog);
		
		ois.close();
	}
}

//Dog类,必须实现Serializable接口
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;
	}

	@Override
	public String toString(){
		return "Dog{" +
				"name='" + name +''' +
				", age=" + age +
				", color='" + color + ''' +
				'}'; 
	}
	
}

本文是学习B站韩顺平老师 IO流 视频的做题笔记,可以参考老师讲解视频:java IO流 韩顺平练习题3

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/592265.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号