RandomAccessFile&&FileChannel

202 阅读1分钟
[root@dev-nfs01 testfileio]# ll
总用量 8
-rw-r--r-- 1 root root 1303 11月 30 15:27 FileTest.java
-rw-r--r-- 1 root root 4096 11月 30 15:29 out.txt
[root@dev-nfs01 testfileio]# pwd
/testfileio
[root@dev-nfs01 testfileio]# cat FileTest.java
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class FileTest{
	public static void main(String[] args) throws Exception{
		RandomAccessFile raf = new RandomAccessFile("/testfileio/out.txt", "rw");
        raf.write("hello haha\n".getBytes());
        raf.write("hello lingqingxia\n".getBytes());
        System.out.println("write------------");
        System.in.read();
        raf.seek(4);
        raf.write("ooxx".getBytes());
        System.out.println("seek---------");
        System.in.read();
        FileChannel rafchannel = raf.getChannel();
        MappedByteBuffer map = rafchannel.map(FileChannel.MapMode.READ_WRITE, 0, 4096);
        map.put("@@@".getBytes());  // 不是系统调用  但是数据会到达 内核的pagecache
        System.out.println("map--put--------");
        System.in.read();
        raf.seek(0);
        ByteBuffer buffer = ByteBuffer.allocate(8192);
        int read = rafchannel.read(buffer);   
        System.out.println(buffer);
        buffer.flip();
        System.out.println(buffer);
        for (int i = 0; i < buffer.limit(); i++) {
            Thread.sleep(200);
            System.out.print(((char)buffer.get(i)));
        }
	}
}
[root@dev-nfs01 testfileio]# javac FileTest.java && java FileTest
write------------

seek---------

map--put--------

java.nio.HeapByteBuffer[pos=4096 lim=8192 cap=8192]
java.nio.HeapByteBuffer[pos=0 lim=4096 cap=8192]
@@@looxxha
hello lingqingxia

[root@dev-nfs01 testfileio]# cat out.txt

[root@dev-nfs01 testfileio]# cat out.txt
hello haha
hello lingqingxia
[root@dev-nfs01 testfileio]# cat out.txt
hellooxxha
hello lingqingxia
[root@dev-nfs01 testfileio]# cat out.txt
@@@looxxha
hello lingqingxia