Randomly Accessing Files (2)
12 December 2007It is assumed that you have gone through the first part (Randomly Accessing Files (1)). In this post, I will write some more examples to show interesting things that can be done using RandomAccessFile object.
An interesting thing that should be kept in mind with dealing with RandomAccessFile object is that there is a pointer that is moved when you read a character, byte or a line. The next read or write operation will occur from the current position of the file pointer. If you wish to move the pointer to a place, you can use seek method.
In the example below, the pointer is moved at the end of the file and current date/time is appended.
File file = new File("C:\\demo.txt"); RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(file.length()); raf.write(0x0A); raf.writeBytes("File checked at: " + new Date()); raf.close();
We have the following text file:
demo.txt
Lets learn Java by examples. Java 6 is the newest one.
We will read the first line, display it on the console and then will add a line to the file.
File file = new File("C:\\demo.txt"); RandomAccessFile raf = new RandomAccessFile(file, "rw"); System.out.println(raf.readLine()); raf.write(0x0A); raf.writeBytes("This line is added by application."); raf.close();
Output:
Lets learn Java by examples.
demo.txt (updated)
Lets learn Java by examples.
This line is added by application.So what we have here. The last line of demo.txt is overwritten by our application. The text was written from the current pointer position and everything from there till the end of written line is overwritten.
Following example shows how to move pointer to a specified place in the file and then read from there.
File file = new File("C:\\demo.txt"); RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(10); System.out.println(raf.readLine());
If you want to append a line in between some file text, you have to be very careful. A simple way is to copy and store the text from where you want to write into a StringBuffer, after writing, append the saved text so nothing will be lost. I will write a post on this soon.
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Randomly Accessing Files (2)