RandomAccessFile
In this chapter you will learn:
- How to use RandomAccessFile
- How to create a RandomAccessFile in read mode
- How to seek position with RandomAccessFile
- How to get file length from RandomAccessFile
- How to read into a byte array
- Read a single byte
- Seek position in a RandomAccessFile
- How to write byte array into RandomAccessFile
- How to write a String to a RandomAccessFile
Use RandomAccessFile
RandomAccessFile encapsulates a random-access file. It is not derived from InputStream or OutputStream.
Instead, it implements the interfaces DataInput and DataOutput, which define the basic I/O methods.
RandomAccessFile
implements the Closeable
interface.
RandomAccessFile
supports positioning
requests, you can position the file pointer within the file.
It has these two constructors:
RandomAccessFile(File fileObj, String access) throws FileNotFoundException
fileObj
specifies the name of the file to open as a File object.RandomAccessFile(String filename, String access) throws FileNotFoundException
the name of the file is passed in filename.
access
parameter determines what type of file access is permitted.
access | Meaning |
---|---|
r | the file can be read, but not written. |
rw | opened in read-write mode. |
rws | opened for read-write operations and every change (data and metadata) will be immediately written to the physical device. |
rwd | opened for read-write operations and every change to the file's data will be immediately written to the physical device. |
The method seek( )
sets the current position of the file pointer within the file:
void seek(long newPos) throws IOException
newPos
specifies the new position, in bytes,
of the file pointer from the beginning of the file.
After a call to seek( )
, the next read or
write operation will occur at the new file position.
It includes some additional methods.
One is setLength( )
. It has this signature:
void setLength(long len) throws IOException
This method sets the length of the invoking file to that specified by len. This method can be used to lengthen or shorten a file. If the file is lengthened, the added portion is undefined.
Create RandomAccessFile in read mode
import java.io.RandomAccessFile;
// j ava 2 s . c om
public class MainClass {
public static void main(String args[]) {
try {
RandomAccessFile raf = new RandomAccessFile(args[0], "r");
long position = raf.length();
while (position > 0) {
position -= 1;
raf.seek(position);
byte b = raf.readByte();
System.out.print((char) b);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Seek position
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
/* j a va 2 s.c o m*/
public class Main {
public static void main(String[] argv) throws IOException {
RandomAccessFile randomAccessFile = new RandomAccessFile("test.dat", "r");
randomAccessFile.seek(1000);
FileChannel fileChannel = randomAccessFile.getChannel();
// This will print "1000"
System.out.println("file pos: " + fileChannel.position());
randomAccessFile.seek(500);
// This will print "500"
System.out.println("file pos: " + fileChannel.position());
fileChannel.position(200);
// This will print "200"
System.out.println("file pos: " + randomAccessFile.getFilePointer());
}
}
The file length
import java.io.RandomAccessFile;
//from jav a 2s . com
public class MainClass {
public static void main(String args[]) {
try {
RandomAccessFile raf = new RandomAccessFile(args[0], "r");
long position = raf.length();
while (position > 0) {
position -= 1;
raf.seek(position);
byte b = raf.readByte();
System.out.print((char) b);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Read into a byte array
import java.io.RandomAccessFile;
/* ja v a2s.c o m*/
public class Main {
public static void main(String[] args) throws Exception {
RandomAccessFile randomAccessFile = null;
String line1 = "line\n";
String line2 = "asdf1234\n";
// read / write permissions
randomAccessFile = new RandomAccessFile("yourFile.dat", "rw");
randomAccessFile.writeBytes(line1);
randomAccessFile.writeBytes(line2);
// Place the file pointer at the end of the first line
randomAccessFile.seek(line1.length());
byte[] buffer = new byte[line2.length()];
randomAccessFile.read(buffer);
System.out.println(new String(buffer));
randomAccessFile.close();
}
}
Read a single byte
import java.io.RandomAccessFile;
/* j av a 2 s . c o m*/
public class MainClass {
public static void main(String args[]) {
try {
RandomAccessFile raf = new RandomAccessFile(args[0], "r");
long position = raf.length();
while (position > 0) {
position -= 1;
raf.seek(position);
byte b = raf.readByte();
System.out.print((char) b);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Seek position
import java.io.RandomAccessFile;
/*ja va 2 s . c o m*/
public class MainClass {
public static void main(String args[]) {
try {
RandomAccessFile raf = new RandomAccessFile(args[0], "r");
long position = raf.length();
while (position > 0) {
position -= 1;
raf.seek(position);
byte b = raf.readByte();
System.out.print((char) b);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Write byte array into RandomAccessFile
import java.io.RandomAccessFile;
/*from j a va2 s. c o m*/
public class Main {
public static void main(String[] argv) throws Exception {
RandomAccessFile file = new RandomAccessFile("scores.html", "rw");
for (int i = 1; i <= 6; i++) {
System.out.println(file.readLine());
}
long current = file.getFilePointer();
file.seek(current + 6);
file.write("34".getBytes());
for (int i = 1; i <= 5; i++) {
System.out.println(file.readLine());
}
current = file.getFilePointer();
file.seek(current + 6);
file.write("27".getBytes());
file.close();
}
}
Write String to a RandomAccessFile
import java.io.RandomAccessFile;
/*j a v a 2 s . com*/
public class Main {
public static void main(String[] args) throws Exception {
RandomAccessFile randomAccessFile = null;
String line1 = "line\n";
String line2 = "asdf1234\n";
// read / write permissions
randomAccessFile = new RandomAccessFile("yourFile.dat", "rw");
randomAccessFile.writeBytes(line1);
randomAccessFile.writeBytes(line2);
// Place the file pointer at the end of the first line
randomAccessFile.seek(line1.length());
byte[] buffer = new byte[line2.length()];
randomAccessFile.read(buffer);
System.out.println(new String(buffer));
randomAccessFile.close();
}
}
Next chapter...
What you will learn in the next chapter: