对于InputStream 和OutputStream 来说,它们的实例都是顺序访问流,也就是说,只能对文件进行顺序地读/写。随机访问文件则允许对文件内容进行随机读/写。在java中,类RandomAccessFile 提供了随机访问文件的方法。类RandomAccessFile的声明为:
public class RandomAccessFile extends Object implements DataInput, DataOutput
接口DataInput 中定义的方法主要包括从流中读取基本类型的数据、读取一行数据、或者读取指定长度的字节数。如:readBoolean( )、readInt( )、readLine( )、readFully( ) 等。
接口DataOutput 中定义的方法主要是向流中写入基本类型的数据、或者写入一定长度的字节数组。如:writeChar( )、writeDouble( )、write( ) 等。 下面详细介绍RandomAccessFile类中的方法。
◇ 构造方法:
RandomAccessFile(String name,String mode); //name是文件名,mode
//是打开方式,例如"r"表示只读,"rw"表示可读写,"
RandomAccessFile(File file,String mode); //file是文件对象
◇ 文件指针的操作
long getFilePointer( ); //用于得到当前的文件指针
void seek( long pos ); //用于移动文件指针到指定的位置
int skipBytes( int n ); //使文件指针向前移动指定的n个字节
|