对象序列化
ObjectInputStream/ObjectOutputStream类
实现对象的读写:
ObjectInputStream把对象读入程序
ObjectOutputStream把对象写入磁盘文件
不保存对象的transient和static类型的变量
ObjectOutputStream类
ObjectOutputStream s = new ObjectOutputStream(new FileOutputStream(“文件名”));
s.writeObject(“Today”);//将String对象存到文件中
s.writeObject(new Fate());//构造一个Date对象,存到文件中去
s.flush();//清空缓冲区
ObjectInputStream类
ObjectInputStream s = new ObjectInputStream(new FileInputStream(“文件名”));
String today = (String)s.readObject();
Date date = (Date)s.readObject();
Serializable接口
package java.io;
public interface Serializable{
//there's nothing in here!
}
在声明自己的类的时候加上这个接口
public class MyClass implements Serializable{
...
}
使用transient可以组织对象的某些成员被自动写入文件
创建一个书籍对象输出并读取
import java.io.*;
class Book implements Serializable {
int id;
String name;
String auther;
float price;
public Book(int id,String name,String auther,float price){
this.id = id;
this.name = name;
this.auther = auther;
this.price = price;
}
}
public class SerializableTester {
public static void main(String[] args) throws IOException,ClassNotFoundException{
Book book = new Book(10032,"java","Java",30);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("book.dat"));
oos.writeObject(book);
oos.close();
book = null;
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("book.dat"));
//readObject()方法读取出的是一个Object类型的对象,返回类型为Object类型
book = (Book)ois.readObject();
ois.close();
System.out.println(book.id);
System.out.println(book.name);
System.out.println(book.auther);
System.out.println(book.price);
}
}
Externalizable接口(定制对象的写和读)
API中的说明:
public interface Externalizable extends Serializable
其中有两个方法writeExternal()和readExternal(),因此实现该接口的类必须实现这两个方法
ObjectOutputStream的writeObjext()方法值写入对象的标识,然后调用对象所属类的writeExternal()
ObjectInputStream的readObjext()方法值写入对象的标识,然后调用对象所属类的readExternal()
随机文件读写
RandomAccessFile类
可跳转到文件的任意位置读/写数据
可在随机文件中插入数据,而不破坏该文件的其他数据
实现了DataInput和DataOutput接口,可使用普通的读写方法
有个位置指示器,指向当前读写出的位置,刚打开文件时,文件指示器指向文件的开头处。对文件指针显式操作的方法:
int skipBytes(int n):把文件指针向前移动制定的n个字节
void seek(long):移动文件指针到指定的位置
long getFilePointer():得到当前的文件指针
在等长记录格式文件的随机读取时有很大的优势,但仅限于操作文件不能访问其他IO设备,如网络、内存映像等
构造方法
public RandonAccessFile(File file,String mode) throws FileNotFoundException
public RandonAccessFile(String name,String mode) throws FileNotFoundException
构造RandomAccessFile对象时,要指出操作:仅读/读写
new RandomAccessFile(“farrago.txt”,“r”);
new RandomAccessFile(“farrago.txt”,“rw”);