Java file seek


 

Java file seek

This section illustrates you the use of seek() method.

This section illustrates you the use of seek() method.

Java file seek

This section illustrates you the use of seek() method.

Description of code:

The java.io.* package provides several input output streams. But there is only one stream that lets you both read and write to it and allow you to move to any point within the file to carry out operations. This stream is RandomAccessFile. This class has two arguments, one of which is a File object or filename to specify the file. A second argument determines the access mode for the file, 'r' for reading and 'rw' for both reading and writing.

If you want to perform operations(read or write) from particular position, then there is a need of method seek() that allows you to specify the index from where the read and write operations will start. You can see in the given example, we have created an object of RandomAccessFile class and pass file object and 'rw' mode as an arguments. Using the method seek() we have set the file pointer at the end of the file and write some text into it.

writeBytes method- This method of RandomAccessFile writes the string into the file.

Here is the code:

import java.io.File;
import java.io.RandomAccessFile;

public class FileSeek {
	public static void main(String[] args) throws Exception {
		File file = new File("c:/abc.txt");
		RandomAccessFile access = new RandomAccessFile(file, "rw");
		System.out.println(access.readLine());
		access.seek(file.length());
		access.writeBytes("Truth is more important than facts");
		access.close();
	}
}

Through the method seek(), you can set the particular index and can perform operations from that index.

Ads