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寫入示例
這是一個簡單的示例,展示了如何使用RandomAccessFile在Java中將數據寫入文件中。
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的全部內容。
Source:
https://www.digitalocean.com/community/tutorials/java-randomaccessfile-example