(Java学习随堂笔记)对象序列化、随机文件读写

对象序列化

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”);

RandomAccessFile类常用的API

## RandomAccessFile类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值