用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - java代码库

java 对象流 以对象数据为单位进行读写 (Serializable)

2012-10-23 作者: 神马举报

[java]代码库

import java.io.*;
import java.util.*;

/**
 * 对象流
 * 
 * 以对象数据为单位进行读写
 * 
 */
public class ObjectFileTest {
	public static void main(String[] args) {
		try {
			Employee[] staff = new Employee[3];
			staff[0] = new Employee("Harry Hacker", 35000,
					new Date(1989, 10, 1));
			staff[1] = new Manager("Carl Cracker", 75000,
					new Date(1987, 12, 15));
			staff[2] = new Employee("Tony Tester", 38000, new Date(1990, 3, 15));
			int i;

			System.out.println("Before writeObject:");
			for (i = 0; i < staff.length; i++)
				staff[i].print();
			ObjectOutputStream out = new ObjectOutputStream(
					new FileOutputStream("employee.dat"));
			out.writeObject(staff);
			out.close();

			ObjectInputStream in = new ObjectInputStream(new FileInputStream(
					"employee.dat"));
			Employee[] newStaff = (Employee[]) in.readObject();

			for (i = 0; i < newStaff.length; i++)
				newStaff[i].raiseSalary(100);
			System.out.println("After readObject:");
			for (i = 0; i < newStaff.length; i++)
				newStaff[i].print();
		} catch (Exception e) {
			System.out.print("Error: " + e);
			System.exit(1);
		}
	}
}

class Employee implements Serializable {
	private String name;
	private double salary;
	private Date hireDay;

	public Employee(String n, double s, Date d) {
		name = n;
		salary = s;
		hireDay = d;
	}

	public Employee() {
	}

	public void print() {
		System.out.println(name + " " + salary + " " + hireYear());
	}

	public void raiseSalary(double byPercent) {
		salary *= 1 + byPercent / 100;
	}

	public int hireYear() {
		return hireDay.getYear();
	}
}

class Manager extends Employee {
	private String secretaryName;

	public Manager(String n, double s, Date d) {
		super(n, s, d);
		secretaryName = "";
	}

	public Manager() {
	}

	public void raiseSalary(double byPercent) {
		Date today = new Date();
		double bonus = 0.5 * (today.getYear() + 1900 - hireYear());
		super.raiseSalary(byPercent + bonus);
	}

	public void setSecretaryName(String n) {
		secretaryName = n;
	}

	public String getSecretaryName() {
		return secretaryName;
	}
}


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...