RandomAccessFile Read/Write Example
This program demonstrates combined read and write using RandomAccessFile.
Problem Statement
Write a Java program that reads and writes data in the same file using RandomAccessFile.
Source Code
| 1 | import java.io.*; |
| 2 | public class RandomReadWriteExample { |
| 3 | public static void main(String[] args) { |
| 4 | System.out.println("Eduinq RandomAccessFile Read/Write Example"); |
| 5 | try(RandomAccessFile raf=new RandomAccessFile("sample.txt","rw")) { |
| 6 | raf.seek(0); |
| 7 | raf.writeBytes("Eduinq"); |
| 8 | raf.seek(0); |
| 9 | String line=raf.readLine(); |
| 10 | System.out.println("Eduinq Data: "+line); |
| 11 | } catch(Exception e){ System.out.println("Eduinq Exception: "+e.getMessage()); } |
| 12 | } |
| 13 | } |
Program Output
Eduinq RandomAccessFile Read/Write Example Eduinq Data: Eduinq
Explanation
Writes data at start of file. - Reads back same data. - Exception handling ensures safe operations. - In enterprise systems, combined read/write supports log updates. Conclusion: Shows combined read/write with RandomAccessFile.