任务描述
本关任务:使用 RandomAccessFile 实现向给定文件中追加给定内容。
相关知识
什么是随机访问文件流(RandomAccessFile)
之前我们学习的文件字符流和文件字节流都是按照文件内容的顺序来读取和写入的。而随机访问文件流允许我们在文件的任意地方写入数据,也可以读取任意地方的数据。
随机访问原理
首先把随机访问的文件对象看作存储在文件系统中的一个大型 byte 数组,然后通过指向该 byte 数组的光标或索引(即:文件指针 FilePointer)在该数组任意位置读取或写入任意数据。
RandomAccessFile 构造方法
下表是它的构造方法: | 构造方法 | 说明 | | ------------ | ------------ | | RandomAccessFile(File file, String mode) | 通过文件对象创建 RandomAccessFile 对象| | RandomAccessFile(String name, String mode) | 通过文件路径字符串创建 RandomAccessFile 对象 | 以上两个构造方法中的第二个参数 mode 共有以下四种类型: | mode 类型 | 说明 | | ------------ | ------------ | | r | 以只读方式来打开指定文件夹。如果试图对该RandomAccessFile执行写入方法,都将抛出IOException异常 | | rw | 以读、写方式打开指定文件。如果该文件尚不存在,则试图创建该文件 | | rws | 以读、写方式打开指定文件。相对于“rw” 模式,还要求对文件内容或元数据的每个更新都同步写入到底层设备 | | rwd | 以读、写方式打开指定文件。相对于”rw” 模式,还要求对文件内容每个更新都同步写入到底层设备|
构造方法示例:
public static void main(String[] args) throws IOException {String s="C:\\Users\\yy\\Desktop\\d.txt";// 通过文件对象创建RandomAccessFile对象,并指定文件为只读File file = new File(s);try(RandomAccessFile randomAccessFile = new RandomAccessFile(file,"r");// 通过字符串路径创建RandomAccessFile对象,并指定文件为只读RandomAccessFile r = new RandomAccessFile(s, "r");){}}RandomAccessFile 常用方法
下表是它的常用方法:
| 方法名 | 说明 |
|---|---|
| seek() | 指定文件的光标位置,下次读文件数据的时候从该位置读取 |
| getFilePointer() | 就是返回当前的文件光标位置,便于我们后续读取插入 |
| length() | 返回文件的长度,它并不会受光标的影响,只会反应客观的文本长度 |
| read()、read(byte[] b)、read(byte[] b,int off,int len) | 读数据,用法跟字节流和字符流是一样的 |
| writer()、writer(byte[] b)、writer(byte[] b,int off,int len) | 写数据,用法跟字节流和字符流是一样的 |
从指定位置读取文件示例:
public static void main(String[] args) throws IOException {String s="C:\\Users\\yy\\Desktop\\d.txt";// 通过文件对象创建RandomAccessFile对象,并指定文件为只读File file = new File(s);try(RandomAccessFile randomAccessFile = new RandomAccessFile(file,"r");){// 打印文件初始指针位置System.out.println(randomAccessFile.getFilePointer());// 移动文件指针位置randomAccessFile.seek(200);byte[] b=new byte[1024];int hasRead=0;// 循环读取文件while((hasRead=randomAccessFile.read(b))!=-1){// 输出文件读取的内容System.out.print(new String(b,0,hasRead));}// 打印文件指针位置System.out.print(randomAccessFile.getFilePointer());}}执行结果:
03ijbi207以上程序有两处关键代码,一处是创建了 RandomAccessFile 对象,该对象以只读模式打开了 d.txt 文件,这意味着 RandomAccessFile 文件只能读取文件内容,不能执行写入。第二处调用了 seek(200)方法,是指把文件的记录指针定位到第 200 个字节的位置。也就是说程序将从第 200 个字节处开始读取数据。读完数据之后,指针位置移到了第 207 个字节位置。其他部分的代码的读取方式和其他的输入流没有区别。
- import java.io.*;
- import java.util.Arrays;
- import java.util.Scanner;
-
- public class FileTest {
-
- public static void main(String[] args) throws IOException {
- // 请在Begin-End间编写完整代码
- /********** Begin **********/
- // 接收给定的字符串
- Scanner input = new Scanner(System.in);
- String str = input.next();
- // 切割字符串
- String[] arr = str.split(",");
- // 通过文件对象创建RandomAccessFile对象
- File file = new File(arr[0]);
- try (
- RandomAccessFile accessFile = new RandomAccessFile(file,"rw");
- ){
- // 移动指针位置
- accessFile.seek(file.length());
- // 追加给定内容
- accessFile.write(arr[1].getBytes());
- // 打印追加内容后的文件指针位置
- System.out.println(accessFile.getFilePointer());
- }
- /********** End **********/
- }
- }