RandomAccessFile(随机读取类)
对于文件内容的处理操作主要是通过InputStream(Reader)、OutputStream(Writer)来实现的,但是利用这些类实现的内容读取只能够将数据部分部分读取进来,如果说现在有这样一种要求:
给你一个非常庞大的文件,这个文件的大小有20G,如果此时按照传统的IO操作进行读取和分析根本不可能完成,所以这种情况下在Java.io包里面即有一个RandomAccessFile类,这个类可以实现文件的跳跃式的读取,可以只读取中间的部分内容(前提:需要有一个完善的保存形式),数据保存的位数要确定好。
RandomAccessFile类里面定义有如下方法:
- 构造方法:public RandomAccessFile(File file,String mode) throws FileNotFoundException
文件处理模式:r、rw
范例:实现文件的保存
package IO深入操作;
import java.io.File;
import java.io.RandomAccessFile;
public class RandomAccessFile类 {
public static void main(String[] args) throws Exception{
File file = new File("D:\\Test\\test"); //定义操作文件
RandomAccessFile randomAccessFile = new RandomAccessFile(file,"rw"); //读写模式
String[] names = new String[]{"zhangsan","lisi ","wangwu "};
int[] age = new int[]{20,30,16};
for(int x = 0;x < names.length;x++){
randomAccessFile.write(names[x].getBytes()); //写入字符串
randomAccessFile.writeInt(age[x]); //写入数字
}
}
}
RandomAccessFile最大的特点在于数据的读取处理上没因为所有的数据是按照固定的长度进行保存的,所以读取的时候就可以进行跳字节读取:
- 向下跳:public int skipBytes(int n) throws IOException
- 向回跳:public void seek(long pos) throws IOException
范例:读取数据
package IO深入操作;
import java.io.File;
import java.io.RandomAccessFile;
public class RandomAccessFile类 {
public static void main(String[] args) throws Exception{
File file = new File("D:\\Test\\test"); //定义操作文件
RandomAccessFile randomAccessFile = new RandomAccessFile(file,"rw"); //读x写模式
{//读取王五的数据,跳过24位
randomAccessFile.skipBytes(24);
byte[] data = new byte[8];
int len = randomAccessFile.read(data);
System.out.println("姓名:"+new String(data,0,len)+"年龄:"+ randomAccessFile.readInt());
}
{ //读取李四的数据,回跳12位
randomAccessFile.seek(12);
byte[] data = new byte[8];
int len = randomAccessFile.read(data);
System.out.println("姓名:"+new String(data,0,len)+"年龄:"+ randomAccessFile.readInt());
}
{ //读取张三的数据,回跳到头
randomAccessFile.seek(0); //回到顶点
byte[] data = new byte[8];
int len = randomAccessFile.read(data);
System.out.println("姓名:"+new String(data,0,len)+"年龄:"+ randomAccessFile.readInt());
randomAccessFile.close();
}
}
}
整体的使用之中由自定要读取的位置,而后按照知道你个的结构进行数据的读取。