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 ...
随机推荐
- Php开源项目大全
WordPress [PHP开源 博客Blog] WordPress是最热门的开源个人信息发布系统(Blog)之一,基于PHP+MySQL构建.WordPress提供的功能包括: 1.文章发布.分类 ...
- IOS app启动过程
1.main函数 2.UIApplicationMain * 创建UIApplication对象 * 创建UIApplication的delegate对象 3.delegate对象开始处理(监 ...
- Linux学习之查找命令汇总
我们经常在linux要查找某个文件,但不知道放在哪里了,可以使用下面的一些命令来搜索: which 查看可执行文件的位置. whereis 查看文件的位置. ...
- 常用js表单文本域验证
1.验证是否为正确的邮箱地址 注意:本方法只能验证以@a.b结尾的邮箱地址,对于三级及三级以上的邮箱,比如@iie.ac.cn结尾的会出现错误 function isEmail(o){ var reg ...
- Android 多状态按钮 ToggleButton
ToggleButton 选中状态,未选中状态并且需要为不同的状态设置不同的显示文本. 属性: checked="true" ...
- GET方式URL乱码问题解决
打开 tomcat/conf/server.xml 查找下面这部分,在最后增加一段代码就可以了. <Connector port="80" maxHttpHeaderSi ...
- python3 模拟登录网站
最近学习python,因经常登录公积金网站查看公积金缴存还款情况,so网上找了写脚本,修改了一下,方便获取网页中的数据. 使用谷歌浏览器F12查看登录请求内容 1.request header需要参数 ...
- Others in life
耗电量主要是与电机有关,800W电机在48V下的工作电流大约是800/48=16.7A,因此其工作时间主要取决于电池的容量,如果电池容量是20Ah,那么大概也就连续工作1个小时左右,也就是30-40k ...
- SQL Server 启用与禁止触发器
启用: disable trigger trigger_name on {objectName | database_name | server}; 禁用: enable trigger trigge ...
- [Leetcode][Python]20: Valid Parentheses
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 20: Valid Parentheseshttps://oj.leetcod ...