IO流-RandomAccessFile
参考文献
随机访问文件-RandomAccessFile
什么是RandomAccessFile
-
RandomAccessFile
既可以读取文件内容,也可以向文件输出数据.同时,RandomAccessFile
支持“随机访问”的方式,程序快可以直接跳转到文件的任意地方来读写数据. -
由于
RandomAccessFile
可以自由访问文件的任意位置,所以如果需要访问文件的部分内容,而不是把文件从头读到尾,使用 RandomAccessFile 将是更好的选择. -
与
OutputStream、Writer
等输出流不同的是,RandomAccessFile
允许自由定义文件记录指针,RandomAccessFile
可以不从开始的地方开始输出,因此RandomAccessFile
可以向已存在的文件后追加内容.如果程序需要向已存在的文件后追加内容,则应该使用RandomAccessFile
RandomAccessFile
基础方法
构造方法
1 | RandomAccessFile(File file, String mode) |
-
**mode :**第二个参数是指以什么模式创建读写流,此参数有固定的输入值,必须为
r/rw/rws/rwd
其中一个.mode 说明 r
以只读方式打开指定文件.如果尝试对该 RandomAccessFile
指定的文件执行写入操作,将抛出IOException
rw
以读取、写入方式打开指定文件.如果文件不存在,则尝试创建文件 rws
以读取、写入方式打开指定文件.相对于 rw
模式,还要求对文件的内容或元数据的每个更新都同步写入到底层存储设备.默认情况下(在rw
模式下),数据会被缓存,只有当缓存已满或者使用RandomAccessFile.close()
关闭流时才会真正写入文件rwd
与 rws
类似,但仅对文件的内容同步更新到磁盘,而不修改文件的元数据
相关方法
操作文件记录指针
-
long getFilePointer()
:该方法返回文件记录指针的当前位置,即当前读取/写入操作的位置1
2
3
4
5
6
7try (RandomAccessFile file = new RandomAccessFile("data.txt", "rw")) {
// 执行一些操作
long position = file.getFilePointer(); // 获取当前文件记录指针的位置
System.out.println("Current position: " + position);
} catch (IOException e) {
e.printStackTrace();
} -
void seek(long pos)
:该方法将文件记录指针定位到指定的位置pos
1
2
3
4
5
6try (RandomAccessFile file = new RandomAccessFile("data.txt", "rw")) {
// 执行一些操作
file.seek(10); // 将文件记录指针定位到位置10
} catch (IOException e) {
e.printStackTrace();
} -
int skipBytes(int n)
:- 该方法尝试跳过输入的n个字节以丢弃跳过的字节(跳过的字节不读取).
- 返回实际跳过的字节数.
- 如果跳过的字节数少于n,可能是由于任意数量的条件引起的,其中一个可能是在跳过n个字节之前已经到达了文件的末尾.
- 如果n为负数,则不会跳过任何字节.
1
2
3
4
5
6try (RandomAccessFile file = new RandomAccessFile("data.txt", "r")) {
int skippedBytes = file.skipBytes(10); // 跳过10个字节
System.out.println("Skipped bytes: " + skippedBytes);
} catch (IOException e) {
e.printStackTrace();
}
RandomAccessFile
使用示例
指定位置读取文件
1 | public static void main(String[] args) { |
向文件中追加内容
1 | public static void main(String[] args) { |
向文件指定位置插入内容
1 | /** |
RandomAccessFile
使用场景
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 HoleLin's Blog!