一、RandomAccessFile讲解
RandomAccessFile类不属于InputStream或者OutputStream分层结构的一部分,它实现了DataInput和DataOutput。RandomAccessFile用于包含了已知长度记录的文件,我们可以使用seek()方法从一条记录移至另一条,可在一个文件里向前或向后移动,然后读取或修改那部分的记录,不像之前的InputStream和OutputStream的实现类那样,每次都从头开始读取。
构造器要求使用者传入一个变量指出对象只是随机读(“r”),还是读写兼施(“rw”)。getFilePointer()用于了解当前在文件的什么地方,seek()用于移至文件内的一个新地点。length()用于判断文件的最大长度。
二、示例代码
public static void main(String []args){
//mode模式 r只读 rw读写
try{
RandomAccessFile rafile=new RandomAccessFile(new File("e://ram.txt"));
System.out.println("文件长度:"+rafile.length());
//改变光标位置
rafile.seek(3L);
System.out.println("光标的位置:"+rafile.getFilePointer());
//注意光标,覆盖字符
rafile.writeBytes("abc");
int temp;
temp=rafile.read();
while(temp!=-1){
System.out.println("光标的位置:"+rafile.getFilePointer());
System.out.println((char)temp);
temp=rafile.read();//读取下一个
}
rafile.close();
}catch(FileNotFoundException e){
// TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}