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

相关文章

Spring IOC的三种实现方式详解

《SpringIOC的三种实现方式详解》:本文主要介绍SpringIOC的三种实现方式,在Spring框架中,IOC通过依赖注入来实现,而依赖注入主要有三种实现方式,构造器注入、Setter注入... 目录1. 构造器注入(Cons编程tructor Injection)2. Setter注入(Setter

Java function函数式接口的使用方法与实例

《Javafunction函数式接口的使用方法与实例》:本文主要介绍Javafunction函数式接口的使用方法与实例,函数式接口如一支未完成的诗篇,用Lambda表达式作韵脚,将代码的机械美感... 目录引言-当代码遇见诗性一、函数式接口的生物学解构1.1 函数式接口的基因密码1.2 六大核心接口的形态学

Spring IOC控制反转的实现解析

《SpringIOC控制反转的实现解析》:本文主要介绍SpringIOC控制反转的实现,IOC是Spring的核心思想之一,它通过将对象的创建、依赖注入和生命周期管理交给容器来实现解耦,使开发者... 目录1. IOC的基本概念1.1 什么是IOC1.2 IOC与DI的关系2. IOC的设计目标3. IOC

Spring Boot统一异常拦截实践指南(最新推荐)

《SpringBoot统一异常拦截实践指南(最新推荐)》本文介绍了SpringBoot中统一异常处理的重要性及实现方案,包括使用`@ControllerAdvice`和`@ExceptionHand... 目录Spring Boot统一异常拦截实践指南一、为什么需要统一异常处理二、核心实现方案1. 基础组件

java中的HashSet与 == 和 equals的区别示例解析

《java中的HashSet与==和equals的区别示例解析》HashSet是Java中基于哈希表实现的集合类,特点包括:元素唯一、无序和可包含null,本文给大家介绍java中的HashSe... 目录什么是HashSetHashSet 的主要特点是HashSet 的常用方法hasSet存储为啥是无序的

IDEA运行spring项目时,控制台未出现的解决方案

《IDEA运行spring项目时,控制台未出现的解决方案》文章总结了在使用IDEA运行代码时,控制台未出现的问题和解决方案,问题可能是由于点击图标或重启IDEA后控制台仍未显示,解决方案提供了解决方法... 目录问题分析解决方案总结问题js使用IDEA,点击运行按钮,运行结束,但控制台未出现http://

解决Spring运行时报错:Consider defining a bean of type ‘xxx.xxx.xxx.Xxx‘ in your configuration

《解决Spring运行时报错:Considerdefiningabeanoftype‘xxx.xxx.xxx.Xxx‘inyourconfiguration》该文章主要讲述了在使用S... 目录问题分析解决方案总结问题Description:Parameter 0 of constructor in x

解决IDEA使用springBoot创建项目,lombok标注实体类后编译无报错,但是运行时报错问题

《解决IDEA使用springBoot创建项目,lombok标注实体类后编译无报错,但是运行时报错问题》文章详细描述了在使用lombok的@Data注解标注实体类时遇到编译无误但运行时报错的问题,分析... 目录问题分析问题解决方案步骤一步骤二步骤三总结问题使用lombok注解@Data标注实体类,编译时

JSON字符串转成java的Map对象详细步骤

《JSON字符串转成java的Map对象详细步骤》:本文主要介绍如何将JSON字符串转换为Java对象的步骤,包括定义Element类、使用Jackson库解析JSON和添加依赖,文中通过代码介绍... 目录步骤 1: 定义 Element 类步骤 2: 使用 Jackson 库解析 jsON步骤 3: 添

Java中注解与元数据示例详解

《Java中注解与元数据示例详解》Java注解和元数据是编程中重要的概念,用于描述程序元素的属性和用途,:本文主要介绍Java中注解与元数据的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参... 目录一、引言二、元数据的概念2.1 定义2.2 作用三、Java 注解的基础3.1 注解的定义3.2 内