随机访问文件

来源:互联网 发布:网络推广实战宝典pdf 编辑:程序博客网 时间:2024/04/28 06:23

      实际中,常常需要随机访问物理文件,需要用到RandomAcceesFile类.其构造方法是:

      public Random AccessFile(String fileName,String mode).其中,mode="rw"(可读写),"r"(只读).其常用方法是:

      void close();关闭流对象,释放资源

     long length();获得文件的长度

     long getFilePointer();获得文件指针的位置

     int read();读取一个字节数据

     int read(byte[],byteArray):从文件中读取字节数据,并赋值给数组

     String readLine():从文件中读取一行文本

      void seek(long position);将指针移向position位置

     void setLength(long length);设置文件的长度

      void write(int byteValue):以字节方式向文件中写入数据

      void writeBytes(String str): 向文件中写入字节数据.其他类型数据依次类推.

      RandomAccessFile类的优势在于,它集中了文件输入和输出流的功能.使用简便,可以减少代码量.

     下面的例子程序实现了以下功能:可以向文件中写入10行二进制数据,并保存在一个二进制文件中.并实现了对该二进制文件的读取功能.

     import java.io.*;

public class RadomFile {

 public static void main(String args[]) throws IOException{
  
  File newDir=new File("d://java//test2");//创建目录对象//
  File newFile=new File(newDir,"accessFile.dat");//创建文件路径对象
  newFile.createNewFile();//创建文件
  
  
  RandomAccessFile fileA=new RandomAccessFile(newFile,"rw");//以读写方式打开文件newFile.
  for(int i=0;i<10;i++)fileA.writeBytes("This is line"+i+"/n");
  fileA.close();
  System.out.println("File Written");
  
  RandomAccessFile fileB=new RandomAccessFile(newFile,"rw");
  fileB.seek(fileB.length());
  fileB.writeBytes("Append line!"+"/n");
  fileB.close();
  System.out.println("file append");
       
  String record=new String();
  RandomAccessFile fileC=new RandomAccessFile(newFile,"r");//以只读方式打开文件.
  while((record=fileC.readLine())!=null)System.out.println(record);
  fileC.close();
  System.out.println("File Printed");
  
  
 }
}

原创粉丝点击