// Create a new RandomAccessFile object for reading a file RandomAccessFile file = new RandomAccessFile("myfile.txt", "r"); // Skip the first 10 bytes of the file file.skipBytes(10); // Read the next 10 bytes of the file byte[] buffer = new byte[10]; file.read(buffer); System.out.println(new String(buffer)); // Close the file file.close();
// Create a new RandomAccessFile object for writing to a file RandomAccessFile file = new RandomAccessFile("myfile.txt", "rw"); // Write a string to the file file.writeBytes("Hello, world!"); // Skip the first 7 bytes of the file file.skipBytes(7); // Write a different string to the file starting at the 8th byte file.writeBytes("Java is awesome!"); // Close the file file.close();In this example, we create a `RandomAccessFile` object for writing to a file called `myfile.txt`. We then write the string "Hello, world!" to the file. We use `skipBytes` to skip the first 7 bytes of the file, and then write the string "Java is awesome!" starting at the 8th byte of the file. Both of these examples use the `RandomAccessFile` class from the `java.io` package library. This class allows us to work with files in a random access manner, meaning we can read or write data from any position within the file.