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. C#中的USB库 WinUSB

    NET C#中的USB库WinUSB,的libusb - Win32和的libusb - 1.0.使用公共设备类,应用程序与所有未经修改的操作系统和驱动程序.大量的示例代码. http://sourc ...

  2. Java RMI 学习笔记

    概况 功能:提供了客户辅助对象和服务辅助对象,为客户辅助对象创建和服务辅助对象形同的方法. 优点:客户不必写任何网络或I/O代码,调用远程方法就和运行在客户自己的本地JVM上对对象进行的正常方法一样. ...

  3. C++ char和string的区别

    'a'是char, "a"是char string,这两者都是普通的字符和字符串,和C中没什么不同 值得注意的是后者包含两个字符,末尾有一个隐身的'\0'而:string str ...

  4. 开发环境配置--Ubuntu+Qt4+OpenCV(二)

    同系列文章 1. 开发环境配置--Ubuntu+Qt4+OpenCV(一) 2. 开发环境配置--Ubuntu+Qt4+OpenCV(二) 3. 开发环境配置--Ubuntu+Qt4+OpenCV(三 ...

  5. 深度解析Linux通过日志反查入侵

    有一个朋友的服务器发现有入侵的痕迹后来处理解决但是由于对方把日志都清理了无疑给排查工作增加了许多难度.刚好手里有些资料我就整理整理贴出来分享一下.其实日志的作用是非常大的.学会使用通过日志来排查解决我 ...

  6. html 字符串互转DOM

    描述 拼动态HTML 字符串的时候,把HTML转DOM对象设置属性后,在转字符串 var str1="<ul><li>kim</li><li> ...

  7. 【Howie玩docker】-windows下玩docker

    Windows下安装toolbox一直没成功,于是投机取巧,用虚拟机手工打造玩docker的方法. 步骤: 安装虚拟机,安装centos 在win下建立共享文件夹,假如是 f:/share 在cent ...

  8. 50行实现简易HTTP服务器

    话说由于一直很懒,所以博客好像也没怎么更新...今天有空就写一下吧. 最近在看node.js的时候开始对http协议感兴趣了,毕竟node一开始就是为了做web服务器而产生的.于是试着想了一下大概的思 ...

  9. 通过Orchard认识的Autofac

    反射Reflection 这是.Net中获取运行时类型信息的方式,.Net的应用程序由几个部分:'程序集(Assembly)'.'模块(Module)'.'类型(class)'组成,而反射提供一种编程 ...

  10. Windows 8 DirectX 和Xaml UI 混合处理方案

    原文 http://www.cnblogs.com/chenkai/archive/2012/11/29/2794983.html [如果不想读这么长问题描述和通用的解决方案. 可以直接skip 这段 ...