Share on Google+Share on Google+

Java file seek

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* 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:


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

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


Posted on: July 8, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.