您的位置:首页 > 编程语言 > Java开发

java IO之RandomAccessFile

2013-03-29 22:22 218 查看
java IO之RandomAccessFile
RandomAccessFile类的主要功能是完成随机的读取操作,本身也可以直接向文件中保存内容。
如果要想实现随机读取,则在存储数据的时候要保存数据长度的一致性,否则是无法实现功能的。
RandomAccessFile的构造方法
public RandomAccessFile(File file, String mode) throws FileNotFoundException
需要接收一个File类的实例,并设置一个操作的模式:
读模式:r
写模式:w
读写模式:rw
其中最重要的是读写模式,如果操作的文件不存在,则会帮用户自动创建。
使用RandomAccessFile进行写入操作:

import java.io.File;
import java.io.RandomAccessFile;
public class RandomAccessFileDemo {
public static void main(String[] args) throws Exception {
File file = new File("D:" + File.separator + "singsongs.txt");
RandomAccessFile raf = null;
raf = new RandomAccessFile(file, "rw");
// 写入第一条数据
String name = "singsong";
int age = 23;
raf.writeBytes(name);// 以字节的方式将字符串写入
raf.writeInt(age);// 写入整数数据
// 写入第二条数据
name = "lishi   ";
age = 23;
raf.writeBytes(name);// 以字节的方式将字符串写入
raf.writeInt(age);// 写入整数数据
raf.close();
}
}

RandomAccessFile进行读取操作:
在RandomAccessFile操作的时候读取的方法都是从DataInput接口实现而来,有一序列的readXxx()方法,可以读取各种类型的数据。
但是在RandomAccessFile中因为可以实现随机的读取,所以有一系列的控制方法
回到读取取点:public void seek(long pos) throws IOException
跳过多少个字节:public int skipBytes(int n) throws IOException

下面就进行读取操作:

import java.io.File;
import java.io.RandomAccessFile;
public class ReadRandomAccessFileDemo {
public static void main(String[] args) throws Exception {
File file = new File("D:" + File.separator + "singsongs.txt");
RandomAccessFile raf = new RandomAccessFile(file, "r");
byte b[] = null;
String name = null;
int age = 0;
b = new byte[8];
raf.skipBytes(12);
for (int i = 0; i < 8; i++) {
b[i] = raf.readByte();
}
name = new String(b);
age = raf.readInt();// 读取数据
System.out.println("姓名:" + name);
System.out.println("年龄:" + age);
raf.close();
}
}

运行结果:
姓名:lishi
年龄:23


本文出自 “singsong” 博客,请务必保留此出处http://singsong.blog.51cto.com/2982804/1166943
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: