Java RandomAccessFile 示例

Java RandomAccessFile提供了读写文件数据的功能。RandomAccessFile将文件视为文件系统中存储的大型字节数组,并使用光标来移动文件指针位置。

Java RandomAccessFile

RandomAccessFile类是Java IO的一部分。在Java中创建RandomAccessFile的实例时,我们需要提供打开文件的模式。例如,要以只读模式打开文件,我们必须使用“r”,而要进行读写操作,我们必须使用“rw”。使用文件指针,我们可以在随机访问文件的任何位置读取或写入数据。要获取当前文件指针,可以调用getFilePointer()方法,要设置文件指针索引,可以调用seek(int i)方法。如果我们在已经存在数据的任何索引处写入数据,它将被覆盖。

Java RandomAccessFile读取示例

我们可以使用 Java 中的 RandomAccessFile 从文件中读取字节数组。以下是使用 RandomAccessFile 的伪代码来读取文件

RandomAccessFile raf = new RandomAccessFile("file.txt", "r");
raf.seek(1);
byte[] bytes = new byte[5];
raf.read(bytes);
raf.close();
System.out.println(new String(bytes));

在第一行中,我们为文件创建了一个只读模式的 RandomAccessFile 实例。然后在第二行中,我们将文件指针移动到索引 1。我们创建了一个长度为 5 的字节数组,所以当我们调用 read(bytes) 方法时,就会从文件中读取 5 个字节到字节数组中。最后,我们关闭了 RandomAccessFile 资源,并将字节数组打印到控制台上。

Java RandomAccessFile 写入示例

以下是一个简单的示例,展示了如何使用 Java 中的 RandomAccessFile 将数据写入文件。

RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");
raf.seek(5);
raf.write("Data".getBytes());
raf.close();

由于 RandomAccessFile 将文件视为字节数组,写操作可以覆盖数据,也可以向文件追加数据。这完全取决于文件指针的位置。如果指针移动到文件长度之外,然后调用写操作,则文件中将写入垃圾数据。因此,在使用写操作时应注意这一点。

RandomAccessFile 追加示例

我们只需要确保文件指针位于文件末尾以便追加文件内容。以下是使用 RandomAccessFile 进行文件追加的代码。

RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");
raf.seek(raf.length());
raf.write("Data".getBytes());
raf.close();

Java RandomAccessFile 示例

以下是一个完整的 Java RandomAccessFile 示例,包括不同的读写操作。

package com.journaldev.files;

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

public class RandomAccessFileExample {

	public static void main(String[] args) {
		try {
			// 文件内容为 "ABCDEFGH"
			String filePath = "/Users/pankaj/Downloads/source.txt"; 
			
			System.out.println(new String(readCharsFromFile(filePath, 1, 5)));

			writeData(filePath, "Data", 5);
			// 现在文件内容为 "ABCDEData"
			
			appendData(filePath, "pankaj");
			// 现在文件内容为 "ABCDEDatapankaj"
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void appendData(String filePath, String data) throws IOException {
		RandomAccessFile raFile = new RandomAccessFile(filePath, "rw");
		raFile.seek(raFile.length());
		System.out.println("current pointer = "+raFile.getFilePointer());
		raFile.write(data.getBytes());
		raFile.close();
		
	}

	private static void writeData(String filePath, String data, int seek) throws IOException {
		RandomAccessFile file = new RandomAccessFile(filePath, "rw");
		file.seek(seek);
		file.write(data.getBytes());
		file.close();
	}

	private static byte[] readCharsFromFile(String filePath, int seek, int chars) throws IOException {
		RandomAccessFile file = new RandomAccessFile(filePath, "r");
		file.seek(seek);
		byte[] bytes = new byte[chars];
		file.read(bytes);
		file.close();
		return bytes;
	}

}

这就是 Java 中 RandomAccessFile 的全部内容。RandomAccessFile

Source:
https://www.digitalocean.com/community/tutorials/java-randomaccessfile-example