Java的对象不仅可以在内存中调用,还可以在硬盘中存取,需要实现一个Externalizable接口,下面介绍其简单用法
首先,写一个类实现Externalizable接口
import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; public class Car implements Externalizable{ public Car(){} public Car(int id,int price){ this.id = id; this.price = price; } private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } private int price; //写入硬盘的方法 @Override public void writeExternal(out) throws IOException { // TODO Auto-generated method stub System.out.println("开始写入"); out.writeObject(id);//ObjectOutput这个东西也就只有在这能用到了把 out.writeObject(price); out.flush(); out.close(); } //从硬盘读出的方法 @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { // TODO Auto-generated method stub System.out.println("开始读出"); this.id = (int)in.readObject(); this.price = (int)in.readObject(); return; } }
调用方法
Externalizable car1 = new Car(8,2); car1.writeExternal(new ObjectOutputStream(new FileOutputStream(new File("d:/exteral.txt")))); Car car2 = new Car(); car2.readExternal(new ObjectInputStream(new FileInputStream(new File("d:/exteral.txt")))); System.out.println(car2.getId()+" "+car2.getPrice());
不过目测Serializable也可以实现相同的功能,代码如下
import java.io.Serializable; public class Person implements Serializable { private String name; private int age; private int id; public Person(){} public Person(String name,int age,int id){ this.name = name; this.age=age; this.id=id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("d:/person1.txt"))); objectOutputStream.writeObject(new Person("haha",25,1)); objectOutputStream.close(); ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File("d:/person1.txt"))); Person p1 = (Person) objectInputStream.readObject(); objectInputStream.close(); System.out.println(p1.getName()+p1.getAge()+p1.getId());