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

Java NIO FileChannel的更多相关文章

  1. JAVA NIO FileChannel 内存映射文件

      文件通道总是阻塞式的. 文件通道不能创建,只能通过(RandomAccessFile.FileInputStream.FileOutputStream)getChannel()获得,具有与File ...

  2. 【原创】java NIO FileChannel 学习笔记 FileChannel 简介

    java NIO 中FileChannel 的实现类是  FileChannelImpl,FileChannel本身是一个抽象类. 先介绍FileChannel File Channels 是线程安全 ...

  3. 【原创】java NIO FileChannel 学习笔记 FileChannel实现分析 即FileChannelImpl分析

    上文已经说了FileChannel是一个抽象类,FileChannelImpl是其实现,接下来介绍FileChannelImpl,参考代码来自OpenJDK7 首先 public class File ...

  4. 【原创】java NIO FileChannel 学习笔记 新建一个FileChannel

    首先使用FileChannel 的open方法获取一个FileChannel对象.下面这段代码是FileChannel中open方法的代码. public static FileChannel ope ...

  5. Java NIO:FileChannel数据传输

    调用方式 FileChannel dstChannel; FileChannel srcChannel; dstChannel.transferFrom(srcChannel,0,srcChannel ...

  6. Java NIO read/write file through FileChannel

    referee:  Java NIO FileChannel A java nio FileChannel is an channel that is connected to a file. Usi ...

  7. Java NIO学习笔记五 FileChannel(文件通道)

    Java NIO FileChannel Java NIO FileChannel是连接文件的通道.使用FileChannel,您可以从文件中读取数据和将数据写入文件.Java NIO FileCha ...

  8. Java NIO 完全学习笔记(转)

    本篇博客依照 Java NIO Tutorial翻译,算是学习 Java NIO 的一个读书笔记.建议大家可以去阅读原文,相信你肯定会受益良多. 1. Java NIO Tutorial Java N ...

  9. Java NIO 学习总结 学习手册

    原文 并发编程网(翻译):http://ifeve.com/java-nio-all/  源自 http://tutorials.jenkov.com/java-nio/index.html Java ...

随机推荐

  1. MIT-6.828-JOS-lab4:Preemptive Multitasking

    Lab 4: Preemptive Multitasking tags: mit-6.828, os 概述 本文是lab4的实验报告,主要围绕进程相关概念进行介绍.主要将四个知识点: 开启多处理器.现 ...

  2. Spring-Session实现Session共享入门教程

    任何一种技术的出现,都是来解决特定的问题的! 本篇开始学习Spring-Session相关的一些知识学习整理,让我们开始吧! Spring-Session介绍 Spring-Session使用的场景? ...

  3. SQL语句之 多表管理

    SQL语句之 多表管理 一个数据库内通常会有不止一张表,有时候我们要把多张表联系起来,这就需要用到多表管理的语句. 1.外键约束 一个表中的非主键字段,如果在另外一张表中是主键,那么这个字段我们叫它做 ...

  4. VMware虚拟机中CentOS设置固定IP

    因为需要配置固定IP,在网上找了很久终于找到一个可行的例子,自己配置成功了. 1.首先获取你的GATEWAY 方便后面在cento系统配置里使用选取菜单栏:Edit->Virtual Netwo ...

  5. poj 3071 概率dp

    转自:cxlove 题目:有2^n个队,相邻的两两打淘汰赛,,求最后哪个队夺冠的概率最大 dp[i][j]表示第i轮的时候,第j去支队伍赢的概率. 那么dp[i][j]的前提就是i-1轮的时候,j是赢 ...

  6. HDU 3974 Assign the task(简单线段树)

    Assign the task Time Limit: 15000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) ...

  7. Answer Sheet - Both, Either & Neither

    http://www.usingenglish.com/quizzes/answers.php?quiz_id=44 This page displays the answers to the 'Bo ...

  8. 改进架构,实现动态数据源,减少java维护

    怎样不用写java代码来完毕开发? 对于大部分的产品和项目来说.页面变化是很头痛的事情.每次小功能上线,新客户到来,都须要进行定制改造,不断的开发维护.每次开发一方面要修改页面,一方面要修改serve ...

  9. 使用java中replaceAll方法替换字符串中的反斜杠

    今天在项目中使用java中replaceAll方法将字符串中的反斜杠("\")替换成空字符串(""),结果出现如下的异常: java.util.regex.Pa ...

  10. Docker 传奇之 dotCloud

    2010年,几个大胡子年轻人在旧金山成立了一家做 PaaS 平台的公司,起名为「dotCloud」,这个名字让我想起了微软的「DotNet」. dotCloud 主要是基于 PaaS 平台为开发者或开 ...