Java 随机访问文件

Java IO教程 - Java随机访问文件


使用随机访问文件,我们可以从文件读取以及写入文件。

使用文件输入和输出流的读取和写入是顺序过程。

使用随机访问文件,我们可以在文件中的任何位置读取或写入。

RandomAccessFile类的一个对象可以进行随机文件访问。我们可以读/写字节和所有原始类型的值到一个文件。

RandomAccessFile可以使用其readUTF()和writeUTF()方法处理字符串。

RandomAccessFile类不在InputStream和OutputStream类的类层次结构中。

模式

可以在四种不同的访问模式中创建随机访问文件。访问模式值是一个字符串。它们列出如下:

模式 含义
"r" 文件以只读模式打开。
"rw" 该文件以读写模式打开。 如果文件不存在,则创建该文件。
"rws" 该文件以读写模式打开。 对文件的内容及其元数据的任何修改立即被写入存储设备。
"rwd" 该文件以读写模式打开。 对文件内容的任何修改立即写入存储设备。

读和写

我们通过指定文件名和访问模式来创建RandomAccessFile类的实例。

RandomAccessFile  raf = new RandomAccessFile("randomtest.txt", "rw");

随机访问文件具有文件指针,当我们从其读取数据或向其写入数据时,该文件指针向前移动。

文件指针是我们下一次读取或写入将开始的光标。

其值指示光标与文件开头的距离(以字节为单位)。

我们可以通过使用其getFilePointer()方法来获取文件指针的值。

当我们创建一个RandomAccessFile类的对象时,文件指针被设置为零。

我们可以使用seek()方法将文件指针设置在文件中的特定位置。

RandomAccessFile的length()方法返回文件的当前长度。我们可以通过使用其setLength()方法来扩展或截断文件。


例子

以下代码显示如何使用RandomAccessFile对象读取和写入文件。

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class Main {
  public static void main(String[] args) throws IOException {
    String fileName = "randomaccessfile.txt";
    File fileObject = new File(fileName);

    if (!fileObject.exists()) {
      initialWrite(fileName);
    }
    readFile(fileName);
    readFile(fileName);
  }

  public static void readFile(String fileName) throws IOException {
    RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
    int counter = raf.readInt();
    String msg = raf.readUTF();

    System.out.println(counter);
    System.out.println(msg);
    incrementReadCounter(raf);
    raf.close();
  }

  public static void incrementReadCounter(RandomAccessFile raf)
      throws IOException {
    long currentPosition = raf.getFilePointer();
    raf.seek(0);
    int counter = raf.readInt();
    counter++;
    raf.seek(0);
    raf.writeInt(counter);
    raf.seek(currentPosition);
  }

  public static void initialWrite(String fileName) throws IOException {
    RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
    raf.writeInt(0);
    raf.writeUTF("Hello world!");
    raf.close();
  }
}

上面的代码生成以下结果。