日期:2014-05-16  浏览次数:20861 次

随机访问类(RandomAccessFile)
随机访问类(RandomAccessFile)

输入流FileInputStream和输出流 FileOutputStream,实现的是对磁盘文件的顺序读写,而且读写要分别创建不同对象。相比之下RandomAccessFile类则可对文件实现随机读写操作。
RandomAccessFile对象的文件位置指针遵循下面的规律:
·新建RandomAccessFile对象的文件位置指针位于文件的开头处;
·每次读写操作之后,文件位置的指针都相应后移到读写的字节数;
·可以通过getFilePointer方法来获得文件位置指针的位置,通过seek方法来设置文件指针的位置。




构造方法:
RandomAccessFile (”路径+文件名”, String“rw”/”r”)两个参数,
//创建模式:“rw”代表写流,“r”代表读流,


RandomAccessFile常用方法
Void close( ) 
Long length( ) 
Void seek( ) 
##Long getFilePointer( )获得当前指针位置,默认为0 ,
Int read( )从文件当前位置读取一个字节
int read (byte[]b) 
int read (byte[]b,int off,int len) 
Final boolean readBoolean( )从文件当前位置读取boolean类型的一个字节  boolean在内存占1/8
Final char readChar( )从文件中读取2个字节。
Final int readInt( )从文件中读取4个字节。
##Final String readLine( )从文件中读取一行后转为String。
Void write(byte[]b)将字节数组B中的数据写到文件中。
Void write(byte[]b,int off,int len)将 len 个字节从指定字节数组写入到此文件,并从偏移量 off 处开始。
Void write(int b)将指定的数据写到文件中。
Final void writeBoolean(boolean v)将boolean类型的值按单字节的形式写到文件中0或1
Final void writeChar(int v)将char值按2个字节写入到文件中
Final void writeChars(String s)将字符串按字符方式写入到文件中
Final void writeInt(int v)按四个字节将 int 写入该文件,先写高字节


Java代码 
     import java.io.*;  
   class RandomAccessFileDemo  
{  
                              
 
public static void main(String args[])throws IOException  
                              
{  
 
            RandomAccessFile f=new RandomAccessFile("myfile","rw");  
            System.out.println ("File.lelngth:"+(f.length( ))+"B");  
            System.out.println ("File PointPosition:"+f.getFilePointer( ));  
            f.seek(f.length( ));  
            f.writeBoolean(true);  
             f.writeBoolean(false);  
            f.writeChar(’a’);  
            f.writeChars("hello!");  
            System.out.println ("File Length;"+(f.length( ))+"B"); 
 
             f.seek(0);  
             System.out.println (f.readBoolean( ));  
             System.out.println (f.readBoolean( ));  
               //while(f.getFilePointer( )<f.length( ));??  
              System.out.println (f.readLine( ));  
               f.close( );  
                  &nb