learning java NIO 之 RandomFileChannel

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class RandomFileChannelTest {
    public static void main(String[] args) {
        var f = new File("a.txt");
        try {
            var raf = new RandomAccessFile(f, "rw");
            FileChannel randomChannel = raf.getChannel();
            ByteBuffer buffer = randomChannel.map(FileChannel.MapMode.READ_ONLY,0,f.length());
            //将文件指针指向末尾,再写入一样的内容,相当于复制追加。
            randomChannel.position(f.length());
            randomChannel.write(buffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

 

posted @ 2019-08-06 09:07  嵌入式实操  阅读(147)  评论(0编辑  收藏  举报