RadomAccessFile对象
描述:此例实现了InputStream和OutputStream接口 提供了对文件通过字节的读写操作。通过getFilePointer
方法读取,并通过seek
方法设置。实现对文件的中某个位置的读取和写入
构造:
RandomAccessFile(File file,String mode) 创建从中读取和向其中写入(可选)的随机存取文件流,该文件由 File 参数指定。 |
RandomAccessFile(String name,String mode) 创建从中读取和向其中写入(可选)的随机存取文件流,该文件具有指定名称。 |
常用的方法:
void | close() 关闭此随机存取文件流并释放与该流关联的所有系统资源。 |
int | read(byte[] b, int off, int len) 将最多 len 个数据字节从此文件读入字节数组。 |
int | readInt() 从此文件读取一个有符号的 32 位整数。 |
byte | readByte() 从此文件读取一个有符号的八位值。 |
String | readLine() 从此文件读取文本的下一行。 |
void | seek(long pos) 设置到此文件开头测量到的文件指针偏移量,在该位置发生下一个读取或写入操作。 |
| |
int | skipBytes(int n) 尝试跳过输入的 n 个字节以丢弃跳过的字节。 |
void | writeInt(int v) 按四个字节将 int 写入该文件,先写高字节。 |
|
|
示例:
//掌握三个重要点
//第一读取权限。
//第二写入基础数据类型。
//第三指针调整
try {
RandomAccessFile rac = new RandomAccessFile("D:\\aa.txt", "r");
byte[] b = new byte[8]; // 8个字节。两个字
rac.read(b);
System.out.println(new String(b));
// 如果当前盘符中没有这个文件,该对象会在盘符中创建这个文件,如果已有该文件,则从指针指向处开始写入,如果原来指针处有内容会覆盖原内容
RandomAccessFile rac1 = new RandomAccessFile("D:\\aa.txt", "rw");
// 如果在该处直接调用方法write,一个数字只会写入最低的8位,会丢失数字,而调用writeInt则会rac1.writeInt(98);
预留4个字节,不会造成字符丢失
rac1.writeInt(98);
// 设置指针开始写入或开始读取的位置
rac1.seek(8);
//尝试跳过输入的 n 个字节以丢弃跳过的字节。 跳过当前字节的N个字节进行读取和写入
rac1.skipBytes(8); //返回指针的当前位置
rac1.getFilePointer();/
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DataInputStream DataOutputStream
使用:
主要对基础数据类型的IO操作
示例:
try {
DataInputStream dis = new DataInputStream(new FileInputStream(
"data.txt"));
dis.read(new byte[4]);
dis.readInt();
dis.readBoolean();
DataOutputStream dos = new DataOutputStream(new FileOutputStream(
"data.txt"));
dos.write("你好".getBytes());
dos.writeInt(128);
dos.writeBoolean(true);
} catch (IOException e) {
e.printStackTrace();
}