[root@dev-nfs01 testfileio]
总用量 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]
/testfileio
[root@dev-nfs01 testfileio]
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())
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
Thread.sleep(200)
System.out.print(((char)buffer.get(i)))
}
}
}
[root@dev-nfs01 testfileio]
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