Java NIO read/write file through FileChannel
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的更多相关文章
- Java NIO Channel之FileChannel [ 转载 ]
Java NIO Channel之FileChannel [ 转载 ] @author zachary.guo 对于文件 I/O,最强大之处在于异步 I/O(asynchronous I/O),它允许 ...
- Java NIO系列教程(二) Channel通道介绍及FileChannel详解
目录: <Java NIO系列教程(二) Channel> <Java NIO系列教程(三) Channel之Socket通道> Channel是一个通道,可以通过它读取和写入 ...
- JAVA NIO学习二:通道(Channel)与缓冲区(Buffer)
今天是2018年的第三天,真是时光飞逝,2017年的学习计划还没有学习完成,因此继续开始研究学习,那么上一节我们了解了NIO,那么这一节我们进一步来学习NIO相关的知识.那就是通道和缓冲区.Java ...
- Java NIO学习笔记---Channel
Java NIO 的核心组成部分: 1.Channels 2.Buffers 3.Selectors 我们首先来学习Channels(java.nio.channels): 通道 1)通道基础 通道( ...
- JAVA NIO学习记录1-buffer和channel
什么是NIO? Java NIO(New IO)是从Java 1.4版本开始引入的一个新的IO API,可以替代标准的Java IO API.NIO与原来的IO有同样的作用和目的,但是使用的方式完全不 ...
- java NIO中的buffer和channel
缓冲区(Buffer):一,在 Java NIO 中负责数据的存取.缓冲区就是数组.用于存储不同数据类型的数据 根据数据类型不同(boolean 除外),提供了相应类型的缓冲区:ByteBufferC ...
- Java NIO简单介绍(一)
Java NIO( New IO) 是从Java 1.4版本开始引入的 一个新的IO API,可以替代标准的Java IO API. NIO与原来的IO有同样的作用和目的,但是使用的方式完全不同,NI ...
- Java NIO 三大组件之 Channel
Java NIO 之 Channel 一.什么是Channel Channel用于源节点(例如磁盘)与目的节点的连接,它可以进行读取,写入,映射和读/写文件等操作. 在Java NIO中负责缓冲区中数 ...
- JAVA NIO FileChannel 内存映射文件
文件通道总是阻塞式的. 文件通道不能创建,只能通过(RandomAccessFile.FileInputStream.FileOutputStream)getChannel()获得,具有与File ...
随机推荐
- 位运算及在java中的应用整理
计算机编码: 原码 符号位为0表示正数,为1表示负数: 其余各位等同于真值的绝对值. 如:0000 0000 0000 0010 =2,1000 0000 0000 0010 =-2 反码 符号位的用 ...
- iOS调用系统声音与振动
如何调用系统声音?[iphone 调用系统铃声与震动功能] 首先要在工程里加入Audio Toolbox framework这个库,然后在需要调用的文件里#import <AudioToolbo ...
- json(转)
转自:http://www.cnblogs.com/mcgrady/archive/2013/06/08/3127781.html 阅读目录 JSON的两种结构 认识JSON字符串 在JS中如何使用J ...
- Java中如何把两个数组合并为一个
在Java中,如何把两个String[]合并为一个? 看起来是一个很简单的问题.但是如何才能把代码写得高效简洁,却还是值得思考的.这里介绍四种方法,请参考选用. 一.apache-commons 这是 ...
- 《OS X Mountain Lion》 读书杂记
OS X是一个类UNIX操作系统,由底层的Darwin和上层的OS X应用程序框架(Cocoa, Carbon, Quartz等)及Aqua用户界面组成.其中Darwin是一个开源.完整的POSIX- ...
- Qt 之 show,hide,setVisible,setHidden,close 等小结
0QObject::deleteLater()delete obj;析构对象1QWidget::setVisible(bool)使得Widget可见或不可见2QWidget::setHidden(bo ...
- [剖析Javascript原理]1.原生数据类型
一.原生数据类型 JS共有5种原生数据类型: Boolean true或者false String 字符串,在单引号或者双引号之间(不存在字符类型) Number 整数或者浮点数 Null 空 und ...
- project euler 48 Self powers 解决乘法爆long long
题目链接 求 $ 1^1+2^2+\cdots + 1000^{1000} $ %1e10 的结果. 唯一的坑点是会爆longlong, 所以用特殊的乘法. #include <iostream ...
- byte与sbyte的转换
C#实现byte与sbyte的转换 byte[] mByte; sbyte[] mSByte = new sbyte[mByte.Length]; ; i < mByte.Length; i++ ...
- American tour(If you have a chance)
去美国旅游,或出国旅游,英语不精没关系,词汇量不多也没关系,但有一些实用的口语一定要学会哟~ 酒店住宿常用英文 I would like to have a morning Call at 8:00 ...