java filechannel api_File文件操作(一):FileChannel

Java NIO FileChannel

Java NIO FileChannel是连接到文件的通道。 使用文件通道,您可以从文件读取数据,并将数据写入文件。 Java NIO FileChannel类是NIO用于使用标准Java IO API读取文件的替代方法。

FileChannel不能设置为非阻塞模式。 它总是以阻止模式运行。

Opening a FileChannel

在您可以使用FileChannel之前,您必须打开它。 您无法直接打开FileChannel。 您需要通过InputStream,OutputStream或RandomAccessFile获取FileChannel。 以下是通过RandomAccessFile打开FileChannel的方法:

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

FileChannel inChannel = aFile.getChannel();

Reading Data from a FileChanne

要从FileChannel读取数据,您可以调用read()方法之一。 这是一个例子:

ByteBuffer buf = ByteBuffer.allocate(48);

int bytesRead = inChannel.read(buf);

首先分配一个缓冲区。 从FileChannel读取的数据被读入缓冲区。

二来调用FileChannel.read()方法。 此方法将数据从FileChannel读入缓冲区。 read()方法返回的int指示缓冲区中有多少个字节。 如果返回-1,则到达文件结尾。

Writing Data to a FileChannel

将文件写入FileChannel是使用FileChannel.write()方法完成的,该方法采用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);

}

注意在一个while循环中如何调用FileChannel.write()方法。 不能保证write()方法写入FileChannel的字节数。 因此,我们重复write()调用,直到Buffer中已经没有尚未写入通道的字节。

Closing a FileChannel

用完FileChannel后必须将其关闭。如:

channel.close();

FileChannel的position方法

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

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

long pos channel.position();

channel.position(pos +123);

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

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

FileChannel Size

FileChannel实例的size()方法将返回该实例所关联文件的大小

long fileSize = channel.size();

FileChannel的truncate方法

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

channel.truncate(1024);

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

FileChannel的force方法

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

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

下面的例子同时将文件数据和元数据强制写到磁盘上:

channel.force(true);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值