import java.nio.file.*;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import static java.nio.file.StandardOpenOption.*;
public class RandomAccessTest
{
public static void main(String[] args)
{
Path file =
Paths.get("C:/example/mydata.txt");
String s = "XYZ";
byte[] data = s.getBytes();
ByteBuffer out = ByteBuffer.wrap(data);
FileChannel fc = null;
try
{
fc = (FileChannel)Files.newByteChannel(file, CREATE, WRITE);
// starting at the beginning of the file
fc.position(0);
// as long as there are bytes in the buffer,
while(out.hasRemaining()) {
// write sequence of bytes from the buffer
fc.write(out);
}
// reset the buffer position back to the beginning
out.rewind();
// reposition the file location at offset 22
// NOTE: the unfilled gaps are stored as zero bytes
fc.position(22);
// as long as there are bytes in the buffer,
while(out.hasRemaining()) {
// write sequence of bytes from the buffer
fc.write(out);
}
// reset the buffer position back to the beginning
out.rewind();
// reposition the file location at offset 12
fc.position(12);
while(out.hasRemaining()) {
// write sequence of bytes from the buffer
fc.write(out);
}
fc.close();
}
catch (Exception e)
{
System.out.println("Error message: " + e);
}
}
} // class RandomAccessTest