Java NIO(四)--FileChannel

6 篇文章 0 订阅

一、概述

NIO 中FileChannel可以理解为一个连接到文件的通道,可以通过FileChannel对文件进行读写; 
FileChannel没有非阻塞模式,读写都只有阻塞的方式;

二、操作

打开FileChannel 

在使用FileChannel之前,必须先打开它。但是,我们无法直接打开一个FileChannel,需要通过使用一个InputStream、OutputStream或RandomAccessFile来获取一个FileChannel实例。下面是通过RandomAccessFile打开FileChannel的示例: 

RandomAccessFile fromFile = new RandomAccessFile("D:/fromFile.txt", "rw");
//获取channel
FileChannel fromChannel = fromFile.getChannel();

从FileChannel读取数据 

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

然后,调用FileChannel.read()方法。该方法将数据从FileChannel读取到Buffer中。read()方法返回的int值表示了有多少字节被读到了Buffer中。如果返回-1,表示到了文件末尾。
如:
ByteBuffer buf = ByteBuffer.allocate(1024*4);  
int bytesRead = inChannel.read(buf);  

向FileChannel写数据 

使用FileChannel.write()方法向FileChannel写数据,该方法的参数是一个Buffer。如:
String newData = "New String to write to file..." + System.currentTimeMillis();  
  
ByteBuffer buf = ByteBuffer.allocate(1024*4);  
buf.clear();  
buf.put(newData.getBytes());  
  
buf.flip();  
  
while(buf.hasRemaining()) {  
    channel.write(buf);  
}  
注意FileChannel.write()是在while循环中调用的。因为无法保证write()方法一次能向FileChannel写入多少字节,因此需要重复调用write()方法,直到Buffer中已经没有尚未写入通道的字节。 

关闭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);  

示例

对于资源文件,操作完都是需要关闭的;以下是一个完成读写实例代码:
public static void main(String[] args) throws IOException {


	RandomAccessFile fromFile = new RandomAccessFile("src\\a.txt", "rw");
	RandomAccessFile toFile = new RandomAccessFile("src\\b.txt", "rw");


	// 获取channel
	FileChannel fromChannel = fromFile.getChannel();
	FileChannel toChannel = toFile.getChannel();


	// 定义缓冲大小
	int bufSize = 1024 * 4;


	// 定义缓冲
	ByteBuffer byteBuffer = ByteBuffer.allocate(bufSize);


	int len = 0;


	// 将数据从源channel写入到缓冲区
	while ((len = fromChannel.read(byteBuffer)) != -1) {


		// 切换到读模式
		byteBuffer.flip();


		while (byteBuffer.hasRemaining()) {
			// 读取缓冲区数据写到目标channel
			toChannel.write(byteBuffer);
		}


		// 清空缓冲
		byteBuffer.clear();
	}


	// 释放资源
	toChannel.close();
	fromChannel.close();
	toFile.close();
	fromFile.close();
}

缓冲区的hasRemainning方法返回一个boolean,标识缓冲区中是否还有数据没有读取,写入FileChannel必须在一个循环中,因为write方法无法保证缓冲区的数据一次全部写入;


通过FileChannel直接传输

在两个通道间传输数据,如果其中有一个是FileChannel,可以不使用缓冲区读出、写入的方式进行传输,可以使用FileChannel的transferFrom 和 transferTo 方法;

1. transferFrom

public long transferFrom(ReadableByteChannel src, long position, long count) throws IOException;
 
该方法可以从其他通道直接将数据传输到fileChannel,position参数表示从position开始先目标文件写入数据,count参表示最多写入的数据量,但是不一定会写入这个参数的数据量,如果来源通道没有那么多可读数据的话;该方法返回一个long值表示成功写入通道的数据量;

2. transferTo

public abstract long transferTo(long position, long count, WritableByteChannel target) throws IOException;
 
改方法与transferFrom相反,是将FileChannel的数据直接写入到目标通道,position参数表示从position位置开始读取数据写入,count参数表示要写入数据的大小,但是不一定写入这个参数的数据量,如果这个fileChannel没有那么多数据可以读取的话;该方法返回一个long值,表示实际写入目标通道的数据量;

以下是一个通过transferFrom/transferTo方法复制文件的实例代码:
public static void main(String[] args) throws IOException {

        RandomAccessFile fromFile = new RandomAccessFile("src\\a.txt", "rw");
        RandomAccessFile inFile = new RandomAccessFile("src\\a.txt", "rw");

        FileChannel fromChannel = fromFile.getChannel();
        FileChannel inChannel = inFile.getChannel();

        int position = 0;
        long count = fromChannel.size();

        long successCount = inChannel.transferFrom(fromChannel, position, count);
        //long successCount = fromChannel.transferTo(position, count, inChannel);

        System.out.println(successCount);
    }

文件锁定

FileChannel的锁,与一般的对象锁相似,都是劝告式锁;获取锁后,它不阻止任何形式的数据访问,而是与对象锁相似,程序中可以通过它进行多线程间协调(线程安全处理);

通过FileChannel的lock方法,可以锁定整个文件或指定一部分;
         请求获取的锁有两种:共享锁和排它锁;共享锁可以获取多个,而排它锁只能获取到一个;
由于不同的操作系统对文件系统锁的实现方式不一样,有些实现了共享锁,而另外一些只实现了排它锁;

以下是一个获取文件锁的实例代码,可以通过同时运行多个观察效果:

public static void main(String[] args) throws Exception {
        RandomAccessFile fromFile = new RandomAccessFile("src\\a.txt", "rw");
        FileChannel fromChannel = fromFile.getChannel();

        System.out.println("trying to lock file...");
        int start = 0;
        int end = 10;
        FileLock fileLock = fromChannel.lock(start, end, false);
        System.out.println("after lock");

        System.out.println("pause...");
        Thread.sleep(8000);

        System.out.println("releasing file lock");
        fileLock.release();
        System.out.println("after release.");

        fromChannel.close();
        fromFile.close();
    }

lock 方法中,start、end参数指定锁定文件的部分,第三个boolean参数,true:表示获取共享锁,false:表示获取排它锁; 
还有一个lock()无参的方法,实际是调用:

public final FileLock lock() throws IOException {
        return lock(0L, Long.MAX_VALUE, false);
}

由于不是全部操作系统都支持共享锁,所以就算请求获取共享锁,但是也可能会返回一个排它锁,可以通过isShare方法确定锁类型:
fileLock.isShared();
对此,我们不如直接只使用排它锁,而不是进行isShare逻辑的判断。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值