RandomAccessFile 类java
1. 基本概念dom
java.io.RandomAccessFile类:支持对随机访问文件的读写操做ide
2. 经常使用的方法指针
方法声明 功能介绍对象
RandomAccessFile(String name,String mode) 根据参数指定的名称和模式构造对象blog
r:以只读方式打开资源
rw: 打开一遍读取和写入同步
rwd:打开以便读取和写入,同步文件内容的更新it
rws: 打开以便读取和写入,同步文件内容和元数据的更新io
int read() 读取单个字节的数据
void seek(long pos) 用于设置今后文件的开头开始测量的文件指针偏移量
void write(int b) 将参数指定的单个字节写入
void close() 用于关闭流并释放有关的资源
3. 代码示例
class RandomAccessFileTest {
main(String[] args){
RandomAccessFile raf = null;
try{
// 1. 建立RandomAccessFile类型的对象,与d:/a.txt文件关联
raf = new RandomAccessFile("d:/a.txt","rw");
// 2. 对文件内容进行随机读写操做
// 设置距离文件开头位置的偏移量,从文件开头位置向后偏移3个字节 aellhello
raf.seek(3);
int res = raf.read();
System.out.println("读取到的单个字符是:" + (char)res); // a l
res = raf.read();
System.out.println("读取到的单个字符是:" + (char)res); // h 指向了e
raf.write('2'); // 执行该行代码后覆盖了字符'e'
System.out.println("写入数据成功!");
} catch (IOException e) {
e.printStackTrace();
} finally {
// 3.关闭流对象并释放有关的资源
if (null != raf) {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
4. IO流练习