Android RandomAccessFile Guide: Read & Write Files

In Android, the RandomAccessFile class is used to read and write the contents of a file, allowing you to position to any location in the file for read and write operations. Here are some common methods used with RandomAccessFile:

  1. Create a RandomAccessFile object:
RandomAccessFile randomAccessFile = new RandomAccessFile("file.txt", "rw");

The first parameter is the file path, and the second parameter is the mode, with “rw” indicating read and write mode.

  1. Write data to file.
randomAccessFile.write("Hello, World!".getBytes());
  1. Locate the specified position of the file.
randomAccessFile.seek(5); // 定位到文件的第5个字节位置
  1. Reading the contents of the file.
byte[] buffer = new byte[10];
randomAccessFile.read(buffer);
String content = new String(buffer);
  1. Close the RandomAccessFile object.
randomAccessFile.close();

After using RandomAccessFile, make sure to call the close() method to close the file. Always remember to handle exceptions when using RandomAccessFile, such as file not found or permission denied.

bannerAds