任务描述
本关任务:向给定文件中的指定位置添加给定内容。
编程要求
仔细阅读右侧编辑区内给出的代码框架及注释,在 Begin-End 间编写程序代码,向给定文件中的指定位置添加给定内容,具体要求如下:
- 接收给定的一行字符串(如:/test/a.txt,23,hello。第一部分为给定文件路径,第二部分为插入位置,第三部分为插入内容);
- 向文件中指定位置添加给定内容。
思路点拨:我们可以把插入点之后的内容先读取到临时文件,再把给定内容和临时文件中的内容依次追加到插入点之后。
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class FileTest {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in); // 接收给定字符串
String str = scanner.nextLine();
// 请在Begin-End间编写完整代码
/********** Begin **********/
// 切割字符串
String[] arr = str.split(",");
//创建一个临时文件
File temp = File.createTempFile("temp",null);
temp.deleteOnExit(); // 程序退出时删除临时文件
// 将插入点之后的内容保存到临时文件
try (
RandomAccessFile accessFile = new RandomAccessFile(new File(arr[0]), "rw"); // 以读写的方式创建一个RandomAccessFile对象
FileOutputStream fileOutputStream = new FileOutputStream(temp);
FileInputStream fileInputStream = new FileInputStream(temp);
){
accessFile.seek(Integer.parseInt(arr[1])); // 把文件记录指针定位到给定的插入位置
byte[] bytes = new byte[1024];
int hasRead = 0; // 用于保存实际读取的字节数据
while ((hasRead = accessFile.read(bytes)) != -1) { // 使用循环读取插入点后的数据
fileOutputStream.write(bytes, 0, hasRead); // 将读取的内容写入临时文件
}
// 将给定的内容和临时文件中的内容依次追加到原文件的插入点后
accessFile.seek(Integer.parseInt(arr[1])); // 把文件记录指针重新定位到给定位置
accessFile.write(arr[2].getBytes()); // 追加需要插入的内容
while ((hasRead = fileInputStream.read(bytes)) != -1) { // 追加临时文件中的内容
accessFile.write(bytes, 0, hasRead);
}
}
/********** End **********/
}
}