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 ...
随机推荐
- AngularJS 实战讲义笔记
第一部分 快速上手 1.1 感受AngularJs四大核心特性(MVC, 模块化,指令系统,双向数据绑定)1.2 搭建自动化的前端开发,调试,测试环境 代码编辑工具 (sublime) 断点调试工具 ...
- struts2 + jquery 开发环境下的ajax构建方法(action写法 + struts.xml配置 + js调用代码)
1.action写法 public class RegisterAction extends ActionSupport { private InputStream inputStream; /** ...
- LeakCanary,检测安卓,java内存泄漏
官方中文API地址:http://www.liaohuqiu.net/cn/posts/leak-canary-read-me/
- C# JSON各种查找法
http://blog.csdn.net/yangxiaojun9238/article/details/8490319
- php正则表达式图谱
php 正则表达式分类图:
- 转: ES6异步编程:Generator 函数的含义与用法
转: ES6异步编程:Generator 函数的含义与用法 异步编程对 JavaScript 语言太重要.JavaScript 只有一根线程,如果没有异步编程,根本没法用,非卡死不可. 以前,异步编程 ...
- flex4 日期类型字符串转日期类型(string转Date)(转)
mysql数据库中存储的日期类型通过PHP返回到flex端为字符串类型,这样在flex中进行处理时就必须要将字符串转化为Date类型.如果仅仅是 "年/月/日" 的组合,而没有涉及 ...
- TelephonyManager
每台手机有一个唯一的设备ID
- CSliderCtrl鼠标点击精确定位
实现CSliderCtrl的子类CXXCtrl 响应左键按下消息 ON_WM_LBUTTONDOWN() void CXXCtrl::OnLButtonDown(UINT nFlags, CPoint ...
- Eclipse 配置Tomcat启动参数 Java EE IDE for Web Developers. Version: Helios Service Release 2
因为在开发的过程中出现了PerGen Space.所以需要修改Tomcat的启动参数,郁闷的事情是公司不使用盗版,因此离开了熟悉的一塌糊涂的MyEclipse界面还真的找不到配置Tomat启动参数的地 ...