1.RandomAccessFile:什么是 随机读写流RandomAccessFile???随机读写流RandomAccessFile常用方法有哪些???
学习:第7遍
1.什么是 随机读写流RandomAccessFile???
随机读写流,是一个字节流,可以对文件进行随机读写 随机:可以定位到文件的任意位置进行读写操作,通过移动指针(Pointer)来实现 读写:使用该流既能读取文件,也能写入文件
2. 随机读写流RandomAccessFile常用方法有哪些???
创建:RandomAccessFile raf=new RandomAccessFile(“a.txt”,“rw”) 第二个参数是模式:r只读、rw读写 当文件不存在时: 如果模式为r,会报异常FileNotFoundException 如果模式为rw,会自动创建文件
方法:raf.getFilePointer() 作用;获取当前指针的位置,从0开始
方法:raf.seek(8) 作用; 将指针移动到指定的位置
方法:raf.skipBytes(3) 作用:将指针向后跳过指定的字节,只能往前,不能倒退 ——>
public class TestRandomAccessFile {
public static void main(String
[] args
) {
try(
RandomAccessFile raf
=new RandomAccessFile("a.txt", "rw");
){
System
.out
.println(raf
.getFilePointer());
raf
.write("张三".getBytes());
raf
.write("hello".getBytes());
System
.out
.println(raf
.getFilePointer());
System
.out
.println("写入成功");
raf
.seek(8);
raf
.write("李四".getBytes());
System
.out
.println(raf
.getFilePointer());
raf
.seek(6);
byte[] buffer
=new byte[2];
raf
.read(buffer
);
System
.out
.println(new String(buffer
));
System
.out
.println(raf
.getFilePointer());
raf
.skipBytes(3);
buffer
=new byte[1024*1024];
int num
=-1;
while((num
=raf
.read(buffer
))!=-1){
System
.out
.println(new String(buffer
,0,num
));
}
raf
.seek(8);
raf
.write("赵".getBytes());
System
.out
.println("修改成功");
}catch(IOException e
){
e
.printStackTrace();
}
}
}