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()));
}
}
使用FileChannel来读写文件
最新推荐文章于 2024-10-04 20:48:10 发布