您的位置:首页 > 移动开发 > Objective-C

操作对象的流ObjectOutputStream,ObjectInputStream、随机读取流RandomAccessFile

2016-05-26 22:27 537 查看
ObjectOutputStream,ObjectInputStream

 * 操作对象

public static void writeObject() throws IOException, FileNotFoundException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.object"));
//对象序列化。被序列化的对象必须实现Serializable接口
oos.writeObject(new Person("小强",30));
oos.close();
}

public static void readObject() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.object"));
//对象反序列化 只能操作ObjectOutputStream写入的文件。
Person p =(Person)ois.readObject();
System.out.println(p.getName()+" "+p.getNum());
ois.close();
}

RandomAccessFile
* 不是io体系中的子类
* 特点:
* 1 该对象既能读,又能写。
* 2 该对象内部维护了一个byte数组,并通过指针可以操作数组中的元素
* 3 可以通过getFilePointer方法获取指针的位置,和通过seek方法设置指针的位置。(随机读取)
* 4 其实该对象就是将字节输入流和输出流进行了封装.
* 5 该对象的源或者目的只能是文件。通过构造函数可以看出。

写:

 void
write(byte[] b)


          将 
b.length
 个字节从指定 byte 数组写入到此文件,并从当前文件指针开始。
 void
writeInt(int v)


          按四个字节将 
int
 写入该文件,先写高字节。
public static void writeFile() throws IOException {
//如果文件不存在则创建,存在则不创建。

RandomAccessFile raf = new RandomAccessFile("ranacc.txt", "rw");
raf.write("张三".getBytes());
raf.writeInt(97);
raf.close();

}

 int
read(byte[] b)


          将最多 
b.length
 个数据字节从此文件读入 byte 数组。
 void
seek(long pos)


          设置到此文件开头测量到的文件指针偏移量,在该位置发生下一个读取或写入操作。
 long
getFilePointer()


          返回此文件中的当前偏移量。
读:

public static void readFile() throws IOException {
RandomAccessFile raf = new RandomAccessFile("ranacc.txt", "rw");
//通过seek设置指针的位置。
raf.seek(1*8);//随机的读取。只要指定指针的位置即可
byte[] buf = new byte[4];
raf.read(buf);
String str = new String(buf);
System.out.println(str);
int age = raf.readInt();
System.out.println(age);
System.out.println(raf.getFilePointer());//获取指针的位置

raf.close();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java se java 编程 博客