Last Updated on 28 July 2019   |   Print Email
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.
1. Benefits of Using Random Access File
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
2. How to Use the RandomAccessFile Class
You can create a RandomAccessFile object by supplying the file path as a String or a File object, plus the access mode:
public RandomAccessFile(File file, String mode)
public RandomAccessFile(String name, String mode)
The access mode can be one of the following values:
“r”: reading only mode.
“rw”: reading and writing mode.
“rws”: same as “rw”, plus any changes to the file’s content and its metadata (such as the last modification time) take effect immediately.
“rwd”: same as “rw”, plus any changes to the file’s content, but not its metadata take effect immediately.
For controlling the file pointer, the RandomAccessFile class provides the following methods:
seek(long pos): moves the file pointer to a specified position in the file. The offset is measured in bytes from the beginning of the file. At this position, the next read or write occurs.
skipBytes(int n): moves the file pointer advance n bytes from the current position. This skips over n bytes of input.
getFilePointer(): returns the current position of the file pointer.
For reading and writing, as the RandomAccessFile class implements both the DataOutput and DataInput interfaces, you can use their methods (to name a few):
Reading methods: read(byte[]), readByte(), readInt(), readLong(), etc.
Writing methods: write(byte[]), writeByte(), writeInt(), writeLong(), etc.
Now, let’s see some examples.
3. Reading File Using RandomAccessFile Example
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:
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
4. Writing File Using RandomAccessFile Example
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.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments