What is the method for randomly reading files on Android?
In Android, you can use the RandomAccessFile class to perform random access operations on files. Below is an example code demonstrating how to use the RandomAccessFile class for random file reading:
try {
RandomAccessFile randomAccessFile = new RandomAccessFile("file.txt", "r");
// 设置读取的起始位置
randomAccessFile.seek(10);
// 读取数据
byte[] buffer = new byte[1024];
int bytesRead = randomAccessFile.read(buffer);
// 处理读取的数据
while (bytesRead != -1) {
// 处理读取的数据
// ...
bytesRead = randomAccessFile.read(buffer);
}
// 关闭RandomAccessFile
randomAccessFile.close();
} catch (IOException e) {
e.printStackTrace();
}
In the code above, a RandomAccessFile object is first created, the seek method is called to set the starting position for reading, followed by using the read method to read and process data, and finally closing the RandomAccessFile object. This allows for random access operations on the file.