使用FileChannel来读写文件

package com.synda.fileChannel;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 使用FileChannel来读写文件,可以基于位置来读写文件
 */
public class TestDemo {
    public static void main(String[] args) {

    }
    @Test
    public void write() throws Exception {
        //获取文件通道;
        FileChannel fc = new FileOutputStream(new File("1.txt")).getChannel();
        ByteBuffer buffer = ByteBuffer.wrap("hello".getBytes());
        fc.write(buffer);
        fc.close();
    }
    @Test
    public  void read() throws  Exception{
        FileChannel fc = new FileInputStream(new File("1.txt")).getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(10);
        fc.read(buffer);
        System.out.println(new String(buffer.array()));
    }
}


版权声明:本文为hzy3344520原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。