Java NIO详解(一): FileChannel

2023-12-14 10:58
文章标签 java 详解 nio filechannel

本文主要是介绍Java NIO详解(一): FileChannel,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

概述

FileChannel是用来读,写,映射, 操作文件的channel(概念参见我的另一篇Java NIO概述).

A channel for reading, writing, mapping, and manipulating a file.

获取FileChannel对象有三种方式:

FileInputStream.getChannel();
FileOutputStream.getChannel();
RandomAccessFile.getChannel();
FileChannel特点
  1. 不能注册到selector
  2. 只能阻塞的运行(就是channel的read方法是阻塞的)
  3. FileChannel对象是线程安全的

上代码

public static void testFileNio(){FileInputStream is = null;FileChannel inChannel = null;FileOutputStream fos = null;FileChannel outChannel = null;try {is = new FileInputStream("f:/text.txt");inChannel = is.getChannel();System.out.println("file size --->"+inChannel.size());ByteBuffer buffer = ByteBuffer.allocate(2);System.out.println("buffer init position --->"+buffer.position()+"---- buffer init remaining --->"+buffer.remaining());//这里标记了后面才可以调用buffer.reset(), 而且只能调用一次,//不然会抛出java.nio.InvalidMarkException//buffer.mark();int flag = 0;int i = 1;while(flag != -1){System.out.println("this is "+i+" time");//返回读取的字节数, 当读到末尾时, 可能返回0 或者 -1flag = inChannel.read(buffer);if(flag == -1 || flag == 0){break;}System.out.println("buffer after read , position-->"+buffer.position()+"---remaining-->"+buffer.remaining());//写数据fos = new FileOutputStream(new File("f:/text2.txt"),true);outChannel = fos.getChannel();if(buffer.remaining() > "this is the end".getBytes().length ){buffer.put("this is the end".getBytes());}System.out.println("buffer after append--position-->"+buffer.position()+"---remaining-->"+buffer.remaining()+"--- flag --->"+flag);//开始写, remaining也变成了当前的position,然后将position置为0buffer.flip();System.out.println("buffer after flip  position-->"+buffer.position()+"---remaining-->"+buffer.remaining());while(buffer.hasRemaining()){outChannel.write(buffer);}System.out.println("buffer after write,  position-->"+buffer.position()+"---remaining-->"+buffer.remaining());//和buffer.reset()的区别, buffer.reset()是回到buffer.mark()的位置//此处不能调用buffer.flip(),;//clear方法会将position置0, limit置为capacity, 也就是remaining是capacity的值         buffer.clear();System.out.println("buffer clear position --->"+buffer.position()+"---- buffer  clear remaining --->"+buffer.remaining());i++;}} catch (IOException e) {e.printStackTrace();}finally{//本来想省略以下代码的, 但是还是忍不住唠叨几句//1.空指针判断, 这个应该没啥//2. 为什么不是所有的close操作都写在一个catch块了,而是写的这么冗长// 原因是如果一个close操作抛出异常, 其他close操作依然可以执行; 如果写在一个catch块,第一个close抛出异常的话,  其他close操作都将无法进行if(is != null){try {is.close();} catch (IOException e) {e.printStackTrace();}}if(inChannel != null){try{inChannel.close();}catch (IOException e){e.printStackTrace();}}if(fos != null){try{fos.close();}catch (IOException e){e.printStackTrace();}}if(outChannel != null){try{outChannel.close();}catch(IOException e){e.printStackTrace();}}}
}
//输出结果如下
file size --->10
buffer init position --->0---- buffer init remaining --->2
this is 1 time
buffer after read , position-->2---remaining-->0
buffer after append--position-->2---remaining-->0--- flag --->2
buffer after flip  position-->0---remaining-->2
buffer after write,  position-->2---remaining-->0
buffer clear position --->0---- buffer  clear remaining --->2
this is 2 time
buffer after read , position-->2---remaining-->0
buffer after append--position-->2---remaining-->0--- flag --->2
buffer after flip  position-->0---remaining-->2
buffer after write,  position-->2---remaining-->0
buffer clear position --->0---- buffer  clear remaining --->2
this is 3 time
buffer after read , position-->2---remaining-->0
buffer after append--position-->2---remaining-->0--- flag --->2
buffer after flip  position-->0---remaining-->2
buffer after write,  position-->2---remaining-->0
buffer clear position --->0---- buffer  clear remaining --->2
this is 4 time
buffer after read , position-->2---remaining-->0
buffer after append--position-->2---remaining-->0--- flag --->2
buffer after flip  position-->0---remaining-->2
buffer after write,  position-->2---remaining-->0
buffer clear position --->0---- buffer  clear remaining --->2
this is 5 time
buffer after read , position-->2---remaining-->0
buffer after append--position-->2---remaining-->0--- flag --->2
buffer after flip  position-->0---remaining-->2
buffer after write,  position-->2---remaining-->0
buffer clear position --->0---- buffer  clear remaining --->2
this is 6 time

问题

  1. 既然FileChannel只能阻塞的运行, 不能注册到selector,那么与FileInputStream,FileOutputStream, RandomAccessFile有何区别呢?

    答案: 其实在Java SE API文档里已经给出答案了,如下:

In addition to the familiar read, write, and close operations of byte channels, this class defines the following file-specific
operations:

Bytes may be read or written at an absolute position in a file in a
way that does not affect the channel’s current position.

A region of a file may be mapped directly into memory; for large files
this is often much more efficient than invoking the usual read or
write methods.

Updates made to a file may be forced out to the underlying storage
device, ensuring that data are not lost in the event of a system
crash.

Bytes can be transferred from a file to some other channel, and vice
versa, in a way that can be optimized by many operating systems into a
very fast transfer directly to or from the filesystem cache.

A region of a file may be locked against access by other programs.

参考资料

  • Java8 SE API文档

这篇关于Java NIO详解(一): FileChannel的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/492247

相关文章

基于C++的UDP网络通信系统设计与实现详解

《基于C++的UDP网络通信系统设计与实现详解》在网络编程领域,UDP作为一种无连接的传输层协议,以其高效、低延迟的特性在实时性要求高的应用场景中占据重要地位,下面我们就来看看如何从零开始构建一个完整... 目录前言一、UDP服务器UdpServer.hpp1.1 基本框架设计1.2 初始化函数Init详解

Java中Map的五种遍历方式实现与对比

《Java中Map的五种遍历方式实现与对比》其实Map遍历藏着多种玩法,有的优雅简洁,有的性能拉满,今天咱们盘一盘这些进阶偏基础的遍历方式,告别重复又臃肿的代码,感兴趣的小伙伴可以了解下... 目录一、先搞懂:Map遍历的核心目标二、几种遍历方式的对比1. 传统EntrySet遍历(最通用)2. Lambd

Spring Boot 中 RestTemplate 的核心用法指南

《SpringBoot中RestTemplate的核心用法指南》本文详细介绍了RestTemplate的使用,包括基础用法、进阶配置技巧、实战案例以及最佳实践建议,通过一个腾讯地图路线规划的案... 目录一、环境准备二、基础用法全解析1. GET 请求的三种姿势2. POST 请求深度实践三、进阶配置技巧1

springboot+redis实现订单过期(超时取消)功能的方法详解

《springboot+redis实现订单过期(超时取消)功能的方法详解》在SpringBoot中使用Redis实现订单过期(超时取消)功能,有多种成熟方案,本文为大家整理了几个详细方法,文中的示例代... 目录一、Redis键过期回调方案(推荐)1. 配置Redis监听器2. 监听键过期事件3. Redi

Spring Boot 处理带文件表单的方式汇总

《SpringBoot处理带文件表单的方式汇总》本文详细介绍了六种处理文件上传的方式,包括@RequestParam、@RequestPart、@ModelAttribute、@ModelAttr... 目录方式 1:@RequestParam接收文件后端代码前端代码特点方式 2:@RequestPart接

SpringBoot整合Zuul全过程

《SpringBoot整合Zuul全过程》Zuul网关是微服务架构中的重要组件,具备统一入口、鉴权校验、动态路由等功能,它通过配置文件进行灵活的路由和过滤器设置,支持Hystrix进行容错处理,还提供... 目录Zuul网关的作用Zuul网关的应用1、网关访问方式2、网关依赖注入3、网关启动器4、网关全局变

SpringBoot全局异常拦截与自定义错误页面实现过程解读

《SpringBoot全局异常拦截与自定义错误页面实现过程解读》本文介绍了SpringBoot中全局异常拦截与自定义错误页面的实现方法,包括异常的分类、SpringBoot默认异常处理机制、全局异常拦... 目录一、引言二、Spring Boot异常处理基础2.1 异常的分类2.2 Spring Boot默

基于SpringBoot实现分布式锁的三种方法

《基于SpringBoot实现分布式锁的三种方法》这篇文章主要为大家详细介绍了基于SpringBoot实现分布式锁的三种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、基于Redis原生命令实现分布式锁1. 基础版Redis分布式锁2. 可重入锁实现二、使用Redisso

SpringBoot的全局异常拦截实践过程

《SpringBoot的全局异常拦截实践过程》SpringBoot中使用@ControllerAdvice和@ExceptionHandler实现全局异常拦截,@RestControllerAdvic... 目录@RestControllerAdvice@ResponseStatus(...)@Except

Springboot配置文件相关语法及读取方式详解

《Springboot配置文件相关语法及读取方式详解》本文主要介绍了SpringBoot中的两种配置文件形式,即.properties文件和.yml/.yaml文件,详细讲解了这两种文件的语法和读取方... 目录配置文件的形式语法1、key-value形式2、数组形式读取方式1、通过@value注解2、通过