stream流都是只读或只写的,数据流的外部文件都是顺序的,如果不创建新文件就不能更新它们。因此提供了RandomAccessFile来对文件进行读取和修改。
需要注意的是RandomAccessFile直接继承自Object,不熟与stream结构
首先,
RandomAccessFile类实现了DataInput接口和DataOutput接口。
因此可以读取基本数据类型和字符串(readInt,readDouble,readChar,readBoolean和readUTF)
也可以写基本数据类型和字符串(writeInt,writeDouble,writeChar,writeBoolean和writeUTF)
其次,
RandomAccessFile有两种模式,只读(r)和读写(rw)
RandomAccessFile(file:File,mode:String)
RandomAccessFile(nam:String,mode:String)
需要注意到,创建RandomAccessFile对象必须指定mode,
方法
close()
getFilePointer():long
read():int
read(b:byte[]):int
read(b:byte[],off:int,len:int)
seek(pos:long) 设置文件指针的位置
setLength(newLength:long) 设置文件新长度
skipBytes(int n) 跳过多少个字节
write(int n)
write(b:byte[])
write(b:byte[],off:int,len:int)
import java.io.*;
public class RandomAccessFileTest{
public static void main(String[] args) throws IOException{
int n = Integer.valueOf(args[0]);
RandomAccessFile raf = new RandomAccessFile("inout.dat","rw");
raf.setLength(0);
for(int i = 1; i <= n ;i++){
raf.writeInt(i);
}
System.out.println("File length:" + raf.length());
raf.seek(0);
System.out.println("The first num :" + raf.readInt());
raf.seek(1*4);
System.out.println("The second num :" + raf.readInt());
raf.seek(9*4);
System.out.println("The tenth num:" + raf.readInt());
raf.writeInt(555);
raf.seek(raf.length());
raf.writeInt(999);
System.out.println("File length:" + raf.length());
raf.seek(10*4);
System.out.println("The eleventh num:" + raf.readInt());
}
}
java RandomAccessFileTest 200