JAVA_IO_对象操作流

26 篇文章 0 订阅

将java对象写入文件,或从文件读取转为java对象
ObjectInputStream、ObjectOutputStream

1.编写JavaBean
package test.others;

import java.io.Serializable;

public class Employee implements Serializable{
	
	private static final long serialVersionUID = -8097676852956481296L;
	
	// 使用transient标明该字段不需要写入文件
	private transient String name;
	private double salary;
	
	public Employee() {
	}

	public Employee(String name, double salary) {
		super();
		this.name = name;
		this.salary = salary;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}
}

2.测试对象流操作
package test.others;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;

public class ObjectDemo01 {
	
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		seri("E:/test/seri.txt");
		read("E:/test/seri.txt");
	}
	
	public static void read(String destPath) throws ClassNotFoundException, IOException {
		File file = new File(destPath);
		ObjectInputStream is = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));
		Object obj = is.readObject();
		if (obj instanceof Employee) {
			Employee emp=(Employee)obj;
			System.out.println(emp.getName());
			System.out.println(emp.getSalary());
		}
		
		obj =is.readObject();
		int[] arr=(int[])obj;
		System.out.println(Arrays.toString(arr));
		is.close();
	}
	
	public static void seri(String desPath) throws IOException {
		Employee emp = new Employee("bjxst", 10000);
		int[] arr = {1,2,3,4};
		File dest = new File(desPath);
		
		ObjectOutputStream dos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(dest)));
		
		dos.writeObject(emp);
		dos.writeObject(arr);
		
		dos.close();
	}
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值