A Java NIO FileChannel is a channel that is connected to a file. Using a file channel you can read data from a file, and write data to a file. The Java NIO FileChannel class is NIO's an alternative to reading files with the standard Java IO API.

A FileChannel cannot be set into non-blocking mode. It always runs in blocking mode.

Opening a FileChannel

Before you can use a FileChannel you must open it. You cannot open a FileChannel directly. You need to obtain a FileChannel via an InputStream, OutputStream, or a RandomAccessFile. Here is how you open a FileChannel via a RandomAccessFile:

RandomAccessFile aFile     = new RandomAccessFile("data/nio-data.txt", "rw");
FileChannel inChannel = aFile.getChannel();

Reading Data from a FileChannel

To read data from a FileChannel  you call one of the read() methods. Here is an example:

ByteBuffer buf = ByteBuffer.allocate(48);

int bytesRead = inChannel.read(buf);

First a  Buffer is allocated. The data read from the  FileChannel is read into the Buffer .

Second the FileChannel.read() method is called. This method reads data from the  FileChannel into the Buffer . The int returned by the read() method tells how many bytes were witten into the Buffer . If -1 is returned, the end-of-file is reached.

Writing Data to a FileChannel

Writing data to a  FileChannel is done using the  FileChannel.write() method, which takes a Buffer  as parameter. Here is an example:

String newData = "New String to write to file..." + System.currentTimeMillis();

ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes()); buf.flip(); while(buf.hasRemaining()) {
channel.write(buf);
}

Notice how the  FileChannel.write() method is called inside a while-loop. There is no guarantee of how many bytes the write() method writes to the FileChannel. Therefore we repeat the write() call until the Buffer has no further bytes to write.

Closing a FileChannel

When you are done using a  FileChannel you must close it. Here is how that is done:

channel.close();    

FileChannel Position

When reading or writing to a  FileChannel you do so at a specific position. You can obtain the current position of the FileChannel object by calling the position() method.

You can also set the position of the  FileChannel by calling the position(long pos) method.

Here are two examples:

long pos channel.position();

channel.position(pos +123);

If you set the position after the end of the file, and try to read from the channel, you will get -1 - the end-of-file marker.

If you set the position after the end of the file, and write to the channel, the file will be expanded to fit the position and written data. This may result in a "file hole", where the physical file on the disk has gaps in the written data.

FileChannel Size

The size()  method of the  FileChannel object returns the file size of the file the channel is connected to. Here is a simple example:

long fileSize = channel.size();    

FileChannel Truncate

You can truncate a file by calling the  FileChannel.truncate() method. When you truncate a file, you cut it off at a given length. Here is an example:

channel.truncate(1024);

This example truncates the file at 1024 bytes in length.

FileChannel Force

The  FileChannel.force() method flushes all unwritten data from the channel to the disk. An operating system may cache data in memory for performance reasons, so you are not guaranteed that data written to the channel is actually written to disk, until you call the force() method.

The force() method takes a boolean as parameter, telling whether the file meta data (permission etc.) should be flushed too.

Here is an example which flushes both data and meta data:

channel.force(true);

Ref:

http://tutorials.jenkov.com/java-nio/file-channel.html

最新文章

  1. 把页面上的图表导出为pdf文件,分享一种请求下载文件的方法
  2. DMZ
  3. Power of Cryptography(用double的泰勒公式可行分析)
  4. [NodeJS] Deploy a Node Application with the Now CLI
  5. Delphi - 在ListView中添加一个进度条
  6. IMSDroid遇到注册问题(蘼1S 计3等一下 Android4.4)
  7. 解决nodejs中json序列化时Date类型默认为UTC格式
  8. 【转】 glibc detected *** corrupted double-linked list:错误的原因有如下三种可能
  9. 在使用可变数组过程中遇到*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'问题
  10. Django 系列博客(二)
  11. Django框架----命名空间模式
  12. Redux 学习笔记
  13. SQL server 数据库的数据完整性
  14. 5 -- Hibernate的基本用法 --4 6 Hibernate事务属性
  15. 2018.10.19 NOIP模拟 比特战争(kruskal)
  16. Centos7 nginx安装过程
  17. FCCMBBTN.RES
  18. CAS客户端整合(一) Discuz!
  19. html元素两种分类。替换元素和不可替换元素;块级元素和行内元素
  20. [译]The Python Tutorial#2. Using the Python Interpreter

热门文章

  1. jQuery选择器--简洁又全面(转)
  2. Mysql - 参数修改
  3. MySQL CPU %sys 高的案例分析(三)
  4. 【python学习-5】面向对象的python
  5. Django中的ORM关系映射查询方面
  6. BugkuCTF ---游戏过关 writeup
  7. BZOJ 3339: Rmq Problem 莫队算法
  8. 【原】Redis windows下的环境搭建
  9. 关于 C 语言,我喜欢和讨厌的十件事
  10. Java 中 byte、byte 数组和 int、long 之间的转换