首页 > 技术文章 > 七 FileChannel

gudulijia 2017-02-21 14:32 原文

FileChannel是一个连接到文件的通道,可以通过文件通道读写文件

FileChannel无法设置为非阻塞模式,它总是运行在阻塞模式下。

打开FileChannel

在使用FileChannel之前,必须先打开它,但是,我们无法直接打开一个FileChannel,需要通过使用一个InputStream,OutputStream或RandomAccessFile来获取一个FileChannel,如下列

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

从FileChannel读取数据

调用多个read()方法之一从FileChannel中读取数据

ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = inChannel.read(buf);

首先分配一个Buffer。从FileChannel中读取的数据将被读到Buffer中。

然后调用FileChannel.read()方法。该方法将数据从FileChannel读取到Buffer中,read()方法返回的int值表示了有多少个字节被读到了Buffer中,如果返回-1,表示到了末尾

向FileChannel中写数据

使用FileChannel.write()向FileChannel写数据,该方法的参数是一个Buffer。

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);
}

注意FileChannel.write()是在while循环中调用的,因为无法保证write()的一次能向FileChannel写入多少个字节,因此需要重复调用write()方法,直到Buffer中已经没有尚未写入Channel的字节。

关闭FileChannel

用完FileChannel必须要关闭

channel.close();

FileChannel的position方法

有时需要在FileChannel的某个特定位置进行数据的I/O操作,可以通过调用position()方法获取FileChannel的当前位置。

也可以通过调用position(long pos)方法设置FileChannel的当前位置。

long pos = channel.position();
channel.position(pos+123);

如果将位置设置在文件结束符之后,然后试图从文件通道中读取数据,读方法返回-1--------文件结束标志

如果将位置设置在文件结束符之后,然后向通道写数据,文件将撑大到当前位置并写入数据。这可能导致“文件空洞”,磁盘上物理文件中写入的数据间有空隙。

FileChannel的size()方法

该方法返回关联文件的大小

long fileSize = channel.size();

FileChannel的truncate方法

可以使用truncate()截取一个文件。截取文件时,文件将指定长度后面的部分被删除。

channel.truncate(1024);

 这个例子截取文件前1024字节。

FileChannel的force()方法

FileChannel.force()将通道里尚未写入磁盘的数据强制写道磁盘上,出于性能方面考虑,操作系统会将数据缓存在内存中,所以无法保证写入到FileChannel到数据一定会及时写到磁盘上,要保证这一点,需要调用force()方法。

force()方法有一个boolean类型的参数,指明是否同时将文件元数据写道磁盘上。

channel.force(true);//将文件数据和元数据强制写到磁盘上

转载自并发编程网 – ifeve.com本文链接地址: Java NIO系列教程(七) FileChannel

 

推荐阅读