RandomAccessFile file = new RandomAccessFile("example.txt", "r"); file.seek(10); // move to position 10 in the file byte[] buffer = new byte[20]; file.read(buffer); // read 20 bytes from position 10 System.out.println(new String(buffer)); // print the contents of the buffer file.close();
RandomAccessFile file = new RandomAccessFile("example.txt", "rw"); file.seek(10); // move to position 10 in the file file.write("Hello".getBytes()); // overwrite the next 5 bytes with "Hello" file.close();This code opens a file called example.txt in read-write mode, moves the file pointer to position 10, writes the bytes of the String "Hello" to that position, overwriting the next 5 bytes, and closes the file. The java.io package provides the RandomAccessFile class.