RandomAccessFile类
- 随机读写类
1.可以操作文件
2.按照字节操作,字节流
3.read读和write写都是此类中的api方法
4.能够通过seek()方法随意移动文件的指针
- RandomAccessFile类的两种模式
RandomAccessFile类对文件的随机访问有两种模式
只读模式
读写模式
- 常用的API
1.创建对象
RandomAccessFile(File file,String mode); 创建从中读取和向其中写入的随机访问流,文件通过File指定,模式通过String指定 RandomAccessFile(String file,String mode) 创建从中读取和向其中写入的随机访问流,文件通过String指定,模式通过String指定 mode的取值: "r" 只读模式 read "rw" 读写模式 read write
2.写入操作
Void write(int b) 此方法会根据当前指针所在位置处写入一个字节,只能使用整型的低8位 Void write(byte[] b) 此方法会根据当前指针所在位置处写入一组字节 Void write(byte[] b ,int offset , int len) 将len个字节从指定的byte数组写入文件,并从偏移量offset处开始
3.读取操作
Int read() 从文件中读取出一个byte字节,填充到整型的低8位如果返回-1,表示 读取到文件的末尾 EOF end of file Int read(byte[] b) 从指针指向的位置开始读取若干字节,存储到字节数组中,将读取的字节 按照顺序放在字节数组相对应的位置上 返回值为读取到字节数,也可以说成长度 返回值为-1,则读取到文件的末尾 Int read(byte[] b , int offset , int len) 将最多len个数据字节从文件中读入byte数组中,并从便宜量offset处开始存储
4.void getFilePointer()
返回此文件中的当前偏移量
5.void seek(long position)
设置到此文件开头0到文件指针偏移量,在该位置发生下一处读取或写入操作
- int skipBytest(int n)
用此方法可以跳过一些少量的字节,可以是整数(如果是负数或零就不进行跳过)
- 小例题,用RandomAccessFile写一个复制文件的小例子
/**
*此方法是把文件读入内存
*/
public ArrayList<byte[]> testMethod1() throws Exception {
RandomAccessFile raf = new RandomAccessFile(new File("D:/aa/note.txt"), "r");
ArrayList<byte[]> al = new ArrayList<byte[]>();
int len = 0;
while (true) {
byte[] buf = new byte[1024];
if (len != -1) {
len = raf.read(buf);
al.add(buf);
} else {
break;
}
}
raf.close();
return al;
}
/**
*此方法是把内存写到本地
*/
@Test
public void testMethod2() throws Exception {
ArrayList<byte[]> al = this.testMethod1();
System.out.println("集合长度" + al.size());
Scanner input = new Scanner(System.in);
System.out.println("请输入要查询的字段位置:");
int k = input.nextInt();
if (0 < k && k <= al.size()) {
System.out.println(new String(al.get(k)));
RandomAccessFile raf1 = new RandomAccessFile(new File("D:/aa/word" + k + ".txt"), "rw");
byte[] buf1 = al.get(k);
raf1.write(buf1);
System.out.println("文件位置:D:/aa");
raf1.close();
} else {
System.out.println("输入位置不正确!!");
System.out.println("请输入1~" + al.size() + "之间的数:");
}
}