java IO之RandomAccessFile

RandomAccessFile类的主要功能是完成随机的读取操作,本身也可以直接向文件中保存内容。

如果要想实现随机读取,则在存储数据的时候要保存数据长度的一致性,否则是无法实现功能的。

RandomAccessFile的构造方法

public RandomAccessFile(File file, String mode) throws FileNotFoundException

需要接收一个File类的实例,并设置一个操作的模式:

读模式:r

写模式:w

读写模式:rw

其中最重要的是读写模式,如果操作的文件不存在,则会帮用户自动创建。

使用RandomAccessFile进行写入操作:

  1. import java.io.File; 
  2. import java.io.RandomAccessFile; 
  3. public class RandomAccessFileDemo { 
  4.     public static void main(String[] args) throws Exception { 
  5.         File file = new File("D:" + File.separator + "singsongs.txt"); 
  6.         RandomAccessFile raf = null
  7.         raf = new RandomAccessFile(file, "rw"); 
  8.         // 写入第一条数据 
  9.         String name = "singsong"
  10.         int age = 23
  11.         raf.writeBytes(name);// 以字节的方式将字符串写入 
  12.         raf.writeInt(age);// 写入整数数据 
  13.         // 写入第二条数据 
  14.         name = "lishi   "
  15.         age = 23
  16.         raf.writeBytes(name);// 以字节的方式将字符串写入 
  17.         raf.writeInt(age);// 写入整数数据 
  18.         raf.close(); 
  19.     } 

RandomAccessFile进行读取操作:

RandomAccessFile操作的时候读取的方法都是从DataInput接口实现而来,有一序列的readXxx()方法,可以读取各种类型的数据。

但是在RandomAccessFile中因为可以实现随机的读取,所以有一系列的控制方法

回到读取取点:public void seek(long pos) throws IOException

跳过多少个字节:public int skipBytes(int n) throws IOException

下面就进行读取操作:

  1. import java.io.File; 
  2. import java.io.RandomAccessFile; 
  3. public class ReadRandomAccessFileDemo { 
  4.     public static void main(String[] args) throws Exception { 
  5.         File file = new File("D:" + File.separator + "singsongs.txt"); 
  6.         RandomAccessFile raf = new RandomAccessFile(file, "r"); 
  7.         byte b[] = null
  8.         String name = null
  9.         int age = 0
  10.         b = new byte[8]; 
  11.         raf.skipBytes(12); 
  12.         for (int i = 0; i < 8; i++) { 
  13.             b[i] = raf.readByte(); 
  14.         } 
  15.         name = new String(b); 
  16.         age = raf.readInt();// 读取数据 
  17.         System.out.println("姓名:" + name); 
  18.         System.out.println("年龄:" + age); 
  19.         raf.close(); 
  20.     } 

运行结果:

  1. 姓名:lishi    
  2. 年龄:23