import java.io.*; public class ReadFileExample { public static void main(String[] args) { try { RandomAccessFile file = new RandomAccessFile("myfile.txt", "r"); String line = null; while ((line = file.readLine()) != null) { System.out.println(line); } file.close(); } catch (IOException e) { e.printStackTrace(); } } }
import java.io.*; public class WriteFileExample { public static void main(String[] args) { try { RandomAccessFile file = new RandomAccessFile("myfile.txt", "rw"); file.seek(file.length()); // move pointer to end of file String text = "Hello, World!"; byte[] data = text.getBytes(); file.write(data); file.close(); } catch (IOException e) { e.printStackTrace(); } } }This code writes the string "Hello, World!" to the end of the file "myfile.txt". The RandomAccessFile class belongs to the java.io package, which is a part of the Java Standard Library.