In this Java File IO tutorial, you’ll learn how to use random access file in Java, using the RandomAccessFile class in the java.io package. Let’s see why you need random access file first.
Unlike IO streams that allow reading and writing data sequentially, random access file allows you to read and write a small chunk of data at any position in the file, using a file pointer. By controlling this file pointer, you can move forth and back within the file to perform reading and writing operations, at any position you want, in a random fashion.
Random access file is ideal for manipulating a particular file format at low level, such as reading, creating and updating MP3 files, PDF files, etc and even your own file format.a
You can create a RandomAccessFile object by supplying the file path as a String or a File object, plus the access mode:
The access mode can be one of the following values:
For controlling the file pointer, the RandomAccessFile class provides the following methods:
For reading and writing, as the RandomAccessFile class implements both the DataOutput and DataInput interfaces, you can use their methods (to name a few):
Now, let’s see some examples.
The following code opens a file for reading and writing. It reads 4 bytes to an integer number from the byte 10th in the file. Then it writes one byte at the byte 125th in the file:
String filePath = "Path/To/Your/File"; try { RandomAccessFile randomFile = new RandomAccessFile(filePath, "rw"); randomFile.seek(10); int number = randomFile.readInt(); randomFile.seek(125); randomFile.writeByte(100); randomFile.close(); } catch (IOException ex) { System.err.println("I/O Error: " + ex); }
Here’s a more realistic sample program that uses a RandomAccessFile to read tags metadata (song name, artist, album and year) of a given MP3 file (in ID3v1 format - last 128 bytes at the end of the file):
import java.io.*; /** * This program demonstrates how to use RandomAccessFile to read ID3 tags of * a MP3 file. * * @author www.codejava.net */ public class ReadMP3Tags { static void testReadMP3(String filePath) { try { String mode = "r"; RandomAccessFile randomFile = new RandomAccessFile(filePath, mode); long length = randomFile.length(); randomFile.seek(length - 128); byte[] byteArray = new byte[3]; randomFile.read(byteArray); String tag = new String(byteArray); if (!"TAG".equals(tag)) { System.out.println("This file doesn't support ID3v1"); System.exit(0); } byteArray = new byte[30]; randomFile.read(byteArray); String songName = new String(byteArray); System.out.println("Song name: " + songName); randomFile.read(byteArray); String artist = new String(byteArray); System.out.println("Artist: " + artist); randomFile.read(byteArray); String album = new String(byteArray); System.out.println("Album: " + album); byteArray = new byte[4]; randomFile.read(byteArray); String year = new String(byteArray); System.out.println("Year: " + year); randomFile.close(); } catch (IOException ex) { System.err.println("I/O Error: " + ex); } } public static void main(String[] args) { String filePath = args[0]; testReadMP3(filePath); } }
Run this program like this:
java ReadMP3Tags <mp3_file_path>
For example:
java ReadMP3Tags DontStop.mp3
The output would be:
Song name: Don't Stop 'Til You Get Enough Artist: Michael Jackson Album: Off The Wall Year: 1999
And the following program uses a RandomAccessFile to updates the song name of a given MP3 file (ID3v1 format):
import java.io.*; /** * This program demonstrates how to use RandomAccessFile to update song name of * a MP3 file (ID3v1 format). * * @author www.codejava.net */ public class WriteMP3Tags { static void updateSongName(String filePath, String title) { try { String mode = "rw"; RandomAccessFile randomFile = new RandomAccessFile(filePath, mode); long length = randomFile.length(); randomFile.seek(length - 128); byte[] byteArray = new byte[3]; randomFile.read(byteArray); String tag = new String(byteArray); if (!"TAG".equals(tag)) { System.out.println("This file doesn't support ID3v1"); System.exit(0); } byteArray = new byte[30]; byte[] titleBytes = title.getBytes(); System.arraycopy(titleBytes, 0, byteArray, 0, titleBytes.length); randomFile.write(byteArray); randomFile.close(); } catch (IOException ex) { System.err.println("I/O Error: " + ex); } } public static void main(String[] args) { String filePath = args[0]; String title = args[1]; updateSongName(filePath, title); } }
Run this program like this:
java WriteMP3Tags <mp3_file_path> <title>
For example:
java WriteMP3Tags DontStop.mp3 "Never Stop Until You Win"
You can run the ReadMP3Tags program to verify the update.