referee:  Java NIO FileChannel

A java nio FileChannel is an channel that is connected to a file. Using a file channel you can read data from a file, and write data to a file. NIO is an alternative to reading files with the standard Java IO API.

A FileChannel cannot be set into non-blocking mode, and it's always runs in blocks mode.

Opening a FileChannel

To use an FileChannel, we should firstly open it. And we should obtain a FileChannel via in InputStream, OutputStream, or an RandomAccessFile. Here is how you can open a FileChannel via RandomChannel:

 RandomAccessFile aFile = new RandomAccessFile("./testNewFile.txt", "rw");
FileChannel inChannel = aFile.getChannel();

Reading Data from FileChannel

we use  read() methods to read  data from FileChannel. Here is an example:

        ByteBuffer buf = ByteBuffer.allocate();
int bytesRead = inChannel.read(buf);

Firstly we allocated a buffer, and read data from channel into buffer. And the method FileChannel.read() return an integer tells how many bytes written into the Buffer. If -1 is returned, then it means end-of-file is reached.

Write Data into a FileChannel

We call method FileChannel.write() to write data into the Buffer. Here is an example:

        String newData = "New String to write file..." + System.currentTimeMillis();
ByteBuffer newBuf = ByteBuffer.allocate(48);
newBuf.clear();
newBuf.put(newData.getBytes());
String v = new String(newBuf.array());
System.out.println("content of new byte buffer: " + v);

FileChannel Position

When reading or writing to a FileChannel at an position, we can get the current of the position of the FileChannel object by calling the position() method.

We can set the position value by calling method position(long pos), and here are the examples:

        long pos = fileChannel.position();
System.out.println(pos);
fileChannel.position(pos - );
System.out.println(fileChannel.position());

Note:

The the position value we set bigger than length of channel, and then try to read data from channel,  then we will get minus 1 showing end-of-file.

And if we try to write data to an position bigger than the length of channel, the file will be extended to fit the position and the writing method can run successfully. But this action will cause an "file hole" meaning file on the disk has graps.

FileChannel Size

We can call method size() to get the length of channel

FileChannel Truncate

We can truncate a file by calling the FileChannel.truncate() method. When you truncate a file, we cut it off at a given length.

FileChannel Force

The force method will flush all unwritten data from the channel to the disk. An operating system may cache data in memory for high performance, so we should take flush to keep data consisentency.

        String content = new String("Before flush: " + Files.readAllBytes(Paths.get("testNewFile.txt")));
System.out.println(content); inChannel.force(true); String contentAfterFlush = new String("After flush: " + Files.readAllBytes(Paths.get("testNewFile.txt")));
System.out.println(contentAfterFlush);

程序源代码:

        String newData = "New String to write file..." + System.currentTimeMillis();
ByteBuffer newBuf = ByteBuffer.allocate(48);
newBuf.clear();
newBuf.put(newData.getBytes());
String v = new String(newBuf.array());
System.out.println("content of new byte buffer: " + v); newBuf.flip();
while(newBuf.hasRemaining()){
inChannel.write(newBuf);
}
long pos = inChannel.position();
System.out.println(pos);
inChannel.position(pos - 10);
System.out.println("position of channel: " + inChannel.position()); // size of the file channel
System.out.println("size of channel: "+inChannel.size()); String content = new String(Files.readAllBytes(Paths.get("testNewFile.txt")));
System.out.println(content); inChannel.force(true); String contentAfterFlush = new String(Files.readAllBytes(Paths.get("testNewFile.txt")));
System.out.println(contentAfterFlush); //close file channel
inChannel.close();

Java NIO read/write file through FileChannel的更多相关文章

  1. Java NIO Channel之FileChannel [ 转载 ]

    Java NIO Channel之FileChannel [ 转载 ] @author zachary.guo 对于文件 I/O,最强大之处在于异步 I/O(asynchronous I/O),它允许 ...

  2. Java NIO系列教程(二) Channel通道介绍及FileChannel详解

    目录: <Java NIO系列教程(二) Channel> <Java NIO系列教程(三) Channel之Socket通道> Channel是一个通道,可以通过它读取和写入 ...

  3. JAVA NIO学习二:通道(Channel)与缓冲区(Buffer)

    今天是2018年的第三天,真是时光飞逝,2017年的学习计划还没有学习完成,因此继续开始研究学习,那么上一节我们了解了NIO,那么这一节我们进一步来学习NIO相关的知识.那就是通道和缓冲区.Java ...

  4. Java NIO学习笔记---Channel

    Java NIO 的核心组成部分: 1.Channels 2.Buffers 3.Selectors 我们首先来学习Channels(java.nio.channels): 通道 1)通道基础 通道( ...

  5. JAVA NIO学习记录1-buffer和channel

    什么是NIO? Java NIO(New IO)是从Java 1.4版本开始引入的一个新的IO API,可以替代标准的Java IO API.NIO与原来的IO有同样的作用和目的,但是使用的方式完全不 ...

  6. java NIO中的buffer和channel

    缓冲区(Buffer):一,在 Java NIO 中负责数据的存取.缓冲区就是数组.用于存储不同数据类型的数据 根据数据类型不同(boolean 除外),提供了相应类型的缓冲区:ByteBufferC ...

  7. Java NIO简单介绍(一)

    Java NIO( New IO) 是从Java 1.4版本开始引入的 一个新的IO API,可以替代标准的Java IO API. NIO与原来的IO有同样的作用和目的,但是使用的方式完全不同,NI ...

  8. Java NIO 三大组件之 Channel

    Java NIO 之 Channel 一.什么是Channel Channel用于源节点(例如磁盘)与目的节点的连接,它可以进行读取,写入,映射和读/写文件等操作. 在Java NIO中负责缓冲区中数 ...

  9. JAVA NIO FileChannel 内存映射文件

      文件通道总是阻塞式的. 文件通道不能创建,只能通过(RandomAccessFile.FileInputStream.FileOutputStream)getChannel()获得,具有与File ...

随机推荐

  1. OpenCV学习(1) RGB颜色空间

    1.1彩色空间 颜色是外来的光刺激作用于人的视觉器官而产生的主观感觉,它具有色调.饱和度和亮度三个特性.物体的颜色不仅取决于物体本身,还与光源.周围环境的颜色,以及观察者的视觉系统有关 1.1.1颜色 ...

  2. zabbix监控服务器部署

    1.服务器安装lamp环境 [root@monitor ~]# yum  install gcc gcc-c++ autoconf httpd php mysql mysql-server php-m ...

  3. php中date函数获取当前时间的时区误差解决办法

    例:echo date('Y-m-d H:i:s', time()); 输出时间:2008-10-12 02:32:17 但实际时间是:2008-10-12 10:32:17时间误差8个小时 PHP手 ...

  4. ajax调用后台Java

    //html部分 <input type='text' placeholder='用户名' id="username" name="username" c ...

  5. java.util.Random 类的 nextInt(int num )

    随机产生3个67~295的整数并找出数值居中的数 并输出中间的数例如:100,225和200,输出200 要随机产生某个范围内的整数,用 java.util.Random 类的 nextInt(int ...

  6. spring常量值注入

    <context:property-placeholder location="classpath:resources/*.properties" /> @Value( ...

  7. android ViewHolder 使用

    android中使用ListView   ExpandableListView  数据适配器adapter很多都是自己定义,自己定义数据适配器时,要重写getView.重写getView为了不让每次调 ...

  8. [原]CAS和Shiro在spring中集成

    shiro是权限管理框架,现在已经会利用它如何控制权限.为了能够为多个系统提供统一认证入口,又研究了单点登录框架cas.因为二者都会涉及到对session的管理,所以需要进行集成. Shiro在1.2 ...

  9. C语言入门(6)——C语言常用数学函数

    在编码过程中会经遇到数学运算,幸运的是C语言提供了非常丰富的数学函数库. 在数学中使用函数有时候书写可以省略括号,而C语言要求一定要加上括号,例如sin(pi/2)这种形式.在C语言的术语中,pi/2 ...

  10. cdoj 847 方老师与栈 火车进出战问题

    //其实我是不想写这题的,但是这题让我想起了我年轻的时候 解法:直接模拟栈就好. //另外我年轻时候做的那题数据范围比较小,原理也不一样. //对于序列中的任何一个数其后面所有比它小的数应该是倒序的, ...