天天看点

java中RandomAccessFile 类对文件进行读写

 /*

RandomAccessFile进行文件的读写这个类实现了  Inputstream和 OutputStream 接口 

可以很方便的对文件进行读写操作

*/

import java.io.* ;

class  Test

{

  public static void main(String []args)  throws Exception

 {

   FileTest o1=new FileTest(1,"xiaoming") ;

   FileTest o2=new FileTest(2,"xiaowang");

  FileTest  o3=new FileTest(3,"xiaolizi");

  RandomAccessFile raf=new RandomAccessFile("111.txt","rw");   //读写方式打开文件

  o1.writeFile(raf); 

  o2.writeFile(raf);

  o3.writeFile(raf);   //传递raf

  raf.seek(0);  //文件指针移动到开头

  FileTest  w=new  FileTest() ;     //构造一个控对象来进行访问

  for(int n=0;n<raf.length();n=(byte)raf.getFilePointer())   

  {

      w.readFile(raf); //将读取到的文件内容 写入raf的成员中

      System.out.println(w.num+"   "+w.name);  //读取数据

  }

 }

}

class FileTest

{  

   int num ;

   String name ;

   FileTest()

   {

   }

   FileTest(int num,String name)

    this.num=num ;

    this.name=name ;

   public  void writeFile(RandomAccessFile raf)  throws  Exception

    {

         raf.writeInt(num) ;

         raf.writeUTF(name);  //会在字符串开始位置记录字符的个数

    } 

  public void readFile(RandomAccessFile raf)  throws Exception

 { 

       num=raf.readInt() ;

       name=raf.readUTF() ;