RandomTest.java
import java.io.*;
import java.nio.*;
import java.nio.file.*;
import java.nio.channels.*;
import static java.nio.file.StandardOpenOption.*;
public class RandomTest {
public static void main(String[] args) {
Path file = Paths.get("file.txt");
String s = "I was here!\n";
byte[] data = s.getBytes();
ByteBuffer out = ByteBuffer.wrap(data);
ByteBuffer copy = ByteBuffer.allocate(12);
try (FileChannel fc = (FileChannel.open(file, READ, WRITE))) {
int nread;
do {
nread = fc.read(copy);
} while (nread != -1 && copy.hasRemaining());
fc.position(0);
while (out.hasRemaining()) {
fc.write(out);
}
out.rewind();
long length = fc.size();
fc.position(length-1);
copy.flip();
while (copy.hasRemaining()) {
fc.write(copy);
}
while (out.hasRemaining()) {
fc.write(out);
}
}catch (IOException x) {
System.out.println("I/O Exception: " + x);
}
}
}
file.txt
I was here!
j
jjjjjjjjj
kkkkkkk
kkkkkkj
jjjjjjjj
jjjjd
dddddddd
ddddd
aaaaaaa
dddddd
dddddd
ddddddd
sssssssss
kkkkk
iiii
iijjjjjjjjjjI was here!I was here!
I was here!