一、随机访问类RandomAccessFile
这个类的实例支持对随机访问文件的读取和写入。
1.构造方法介绍:
- RandomAccessFile(File file, String mode) 创建从中读取和向其中写入(可选)的随机访问文件流,该文件由 File 参数指定。
- RandomAccessFile(String name, String mode) 创建从中读取和向其中写入(可选)的随机访问文件流,该文件具有指定名称
构造方法中的mode表示:
- r(reader)表示当前文件支持读操作
- rw(reader、Writer)表示当前文件支持读写操作
- rws(Reader、Writer、synchronize)表示当前文件支持读写操作,并且将文件内容和元数据同步到存储介质
- rwd()表示支持读写操作,并且将文件内容同步到存储介质
2.常用方法:
- long length() 返回此文件的长度
- int read() 从此文件中读取一个数据字节
- int read(byte[] b将最多b.length个数据字节从此文件中读入byte数组
- int read(byte[] b, int off, int len) 将最多 len 个数据字节从此文件读入 byte 数组。
- String readLine() 从此文件读取文本的下一行。
- void seek(long pos) 设置到此文件开头测量到的文件指针偏移量,在该位置发生下一个读取或写入操作。
- long getFilePointer() 返回此文件中的当前偏移量。
- void setLength(long newLength) 设置此文件的长度。
- int skipBytes(int n) 尝试跳过输入的 n 个字节以丢弃跳过的字节。
- void write(byte[] b) 将 b.length 个字节从指定 byte 数组写入到此文件,并从当前文件指针开始。
- void write(int b) 向此文件写入指定的字节。
注意:
int skipBytes(int n)底层是调用了seek()方法,而seek()方法源码中是用native修饰的,底层是C或者C++语言写的
3.代码示例:
public static void main(String[] args) throws IOException {
String path = "C:\\Users\\50579\\Desktop\\tt.txt";
//创建可读的随机访问文件流
RandomAccessFile randomAccessFile = new RandomAccessFile(path,"r");
randomAccessFile.write(1);
randomAccessFile.