1、使用FileChannel 从文件中读取数据
channel是一个通道,通过它可以写入或者读取数据。所有的数据都得通过buffer来处理,
使用NIO来读取数据,一般使用FileChannel的步骤为:
- 1、从FileInputStream中获取到Channel
- 2、创建一个用来存放数据的容器(buffer)
- 3、将数据从channel中读入到buffer中。
/**
* 测试使用FileChannel来读取文件
*/
@Test
public void testFileChannel() throws IOException {
FileInputStream is = new FileInputStream("abc.txt");
FileChannel channel = is.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer);
buffer.flip();
System.out.println(new String(read(buffer)));
}
/**
* 从buffer将数据读取到数组中
* @param buffer
* @return
*/
public static byte[] read(ByteBuffer buffer){
byte[] bytes = new byte[buffer.limit() - buffer.position()];
buffer.get(bytes);
return bytes;
}
2、使用FileChannel 向文件中写入数据
使用NIO写入数据的步骤一般如下:
- 1、从
FileOutputStream获取数据 - 2、创建buffer
- 3、将数据从channel写入buffer
/**
* 测试使用FileChannel来写入文件
* @throws IOException
*/
@Test
public void TestFileChannelWrite() throws IOException {
FileOutputStream os = new FileOutputStream("abc.txt");
FileChannel channel = os.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(26);
//向buffer 中写入26个英文字母
for(byte i= 65;i<65+26;i++){
buffer.put(i);
}
buffer.flip();
channel.write(buffer);
channel.close();
}
写入成功后,我们打开项目根目录下的abc.txt文件查看里
NIO与FileChannel实战

本文详细介绍并演示了如何使用Java NIO中的FileChannel进行文件读写操作,包括从FileInputStream获取Channel,创建Buffer,以及读写数据的具体步骤。

2185

被折叠的 条评论
为什么被折叠?



