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. AJAX应用中必须要掌握的知识!

    AJAX是什么? 是Asynchronous Javascript And XML的首字母的缩写, 它不是一门的新的语言,而是对现有技术的综合利用. 其本质是在HTTP协议的基础上以异步的方式与服务器 ...

  2. Oracle错误ORA-03113: end-of-file on communication channel处理办法

    oracle不能启动了,报错ORA-03113: end-of-file on communication channel (通信通道的文件结尾) 解决办法: SQL> startup ORAC ...

  3. jquery ajax调用

    client: <script type="text/javascript" language="javascript"> function jqu ...

  4. poj2478--欧拉函数打表

    此题中对时间有要求,如直接使用欧拉函数求解,每输入一个n,就得进行循环求出<n的每个数的欧拉函数, 这样会超时, 于是我们可预先将欧拉函数打表, 再进行一个循环加法运算,便可不超时得解. #in ...

  5. Java程序执行Linux命令

    Java程序中要执行linux命令主要依赖2个类:Process和Runtime 首先看一下Process类: ProcessBuilder.start() 和 Runtime.exec 方法创建一个 ...

  6. JS倒计时器一只,顺便复习javascript时间相关函数

    window.onload = function(){ var uS = 604800; //后台提供 : 秒 var day=hour=minute=second=0, timer; var dem ...

  7. 回归 WordPress

    一直很喜欢用WordPress,使用方便,模板容易定制,国内建站可选择的虚拟主机多.自从WordPress升级后,官方网站打不开,从 GitHub 安装 WordPress 后无法浏览在线的主题.一切 ...

  8. Hibernate之总结

    以前做.net,最近做java项目,负责服务端的开发,直接用的jdbc,线程安全问题.缓存同步问题以及连接池什么的,都是手动写,不但麻烦而且容易出错.项目结束,赶快抽时间学了下hibernate,每天 ...

  9. codeforces 659E . New Reform 强连通

    题目链接 对于每一个联通块, 如果有一个强连通分量, 那么这个联通块对答案的贡献就是0. 否则对答案贡献是1. #include <iostream> #include <vecto ...

  10. echarts实现上海地域PM值(map、timeline)

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...