java 输入输出IO流 RandomAccessFile文件的任意文件指针位置地方来读写数据

时间:2023-03-09 17:10:04
java 输入输出IO流  RandomAccessFile文件的任意文件指针位置地方来读写数据

RandomAccessFile的介绍:

RandomAccessFile是Java输入输出流体系中功能最丰富的文件内容访问类,它提供了众多的方法来访问文件内容,它既可以读取文件内容,也可以向文件输出数据。与普通的输入/输出流不同的是,RandomAccessFile 支持"随机访问"的方式,程序可以直接跳转到文件的任意地方来读写数据。
这个类有两个构造器:
  • RandomAccessFile​(File file, String mode) 创建随机访问文件流,以便从File参数指定的文件中读取,也可以选择写入。
  • RandomAccessFile​(String name, String mode) 创建随机访问文件流,以便从具有指定名称的文件进行读取,并可选择写入该文件。
mode:
  • r:表示以只读的方式打开文件,就是说打开的文件只能读取,不能写入,如果写入将抛出异常
  • rw:写方式打开指定文件。如果该文件尚不存在,则尝试创建该文件
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile; /**
* @ClassName RandomAccessFileExample
* @projectName: object1
* @author: Zhangmingda
* @description: XXX
* date: 2021/4/18.
*/
public class RandomAccessFileExample {
public static void main(String[] args) {
String textFilePath = "输入输出文件读写/src/test/input/test.txt";
try(RandomAccessFile randomAccessFile = new RandomAccessFile(textFilePath,"r")) {
//当前文件指针位置
System.out.println(randomAccessFile.getFilePointer()); //0
randomAccessFile.seek(3);
System.out.println(randomAccessFile.getFilePointer()); //3
byte[] bytes = new byte[1024];
int len;
while ((len = randomAccessFile.read(bytes)) != -1){
String str = new String(bytes, 0, len, "utf-8");
System.out.println(str);
/**
*槽,这是测试输入的,你知道么?
* 不知道?
* 不知道拉到。
*/
}
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
}