java NIO 之fileChannel

Java NIO中的FileChannel是一个连接到文件的通道。可以通过文件通道读写文件。FileChannel无法设置为非阻塞模式,它总是运行在阻塞模式下(因为不可以将FileChannel注册到Selector上)。

1、打开FileChannel

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

RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw");
FileChannel inChannel = aFile.getChannel();
2、从FileChannel读取数据

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

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

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

3、向FileChannel写数据

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

ByteBuffer buf = ByteBuffer.allocate(48);
buf.put(newData.getBytes());

buf.flip();

while(buf.hasRemaining()) {
	channel.write(buf);
}

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

4、关闭FileChannel

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

channel.close();

5、FileChannel的position方法

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

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

如果将位置设置在文件结束符之后,然后试图从文件通道中读取数据,读方法将返回-1 —— 文件结束标志。如果将位置设置在文件结束符之后,然后向通道中写数据,文件将撑大到当前位置并写入数据。这可能导致“文件空洞”,磁盘上物理文件中写入的数据间有空隙。

6、FileChannel的size方法

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

long fileSize = channel.size();

7、FileChannel的truncate方法

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

channel.truncate(1024);

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

8、FileChannel的force方法

FileChannel.force()方法将通道里尚未写入磁盘的数据强制写到磁盘上。出于性能方面的考虑,操作系统会将数据缓存在内存中,所以无法保证写入到FileChannel里的数据一定会即时写到磁盘上。要保证这一点,需要调用force()方法。force()方法有一个boolean类型的参数,指明是否同时将文件元数据(权限信息等)写到磁盘上。下面的例子同时将文件数据和元数据强制写到磁盘上:

channel.force(true);
综合实例:

package cn.edu.nuc.MyTestSimple.nio;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class NIOTest {
	static void readNIO() {
		String pathname = "d:\\test.txt";
		FileInputStream fin = null;
		try {
			fin = new FileInputStream(new File(pathname));
			FileChannel channel = fin.getChannel();

			int capacity = 1024;// 字节
			ByteBuffer bf = ByteBuffer.allocate(capacity);
			bf.clear();
			
			int length = -1;

			while ((length = channel.read(bf)) != -1) {
				byte[] bytes = bf.array();
				System.out.write(bytes, 0, length);
				System.out.println();

				//向bf中写数据之前调用clear,将位置置为0,将limit置为容量, 以备下次读入到字节缓冲中,从0开始存储
				bf.clear();
			}
			channel.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fin != null) {
				try {
					fin.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	static void writeNIO() {
		String filename = "d:\\out1.txt";
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(new File(filename));
			FileChannel channel = fos.getChannel();
			
			ByteBuffer src = Charset.forName("utf8").encode("sdfsadfsafsadfdsf");
			int length = 0;
			while ((length = channel.write(src)) != 0) {
				//注意,这里不需要clear,将缓冲中的数据写入到通道中后 第二次接着上一次的顺序往下读
				System.out.println("写入长度:" + length);
			}
			
			//或者使用
			/*ByteBuffer buf = ByteBuffer.allocate(48);
			buf.put("sdfdsfdsfdsf .... hahahaha...........".getBytes());
			buf.flip();
			while(buf.hasRemaining()) {
				channel.write(buf);
			}*/
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	static void testReadAndWriteNIO() {
		String pathname = "d:\\liuxiao.txt";
		FileInputStream fin = null;
		String filename = "d:\\test-out.txt";
		FileOutputStream fos = null;
		try {
			fin = new FileInputStream(new File(pathname));
			FileChannel channel = fin.getChannel();

			int capacity = 100;// 字节
			ByteBuffer bf = ByteBuffer.allocate(capacity);
			System.out.println("限制是:" + bf.limit() + "容量是:" + bf.capacity()
					+ "位置是:" + bf.position());
			int length = -1;

			fos = new FileOutputStream(new File(filename));
			FileChannel outchannel = fos.getChannel();
			while ((length = channel.read(bf)) != -1) {
				// 将当前位置置为limit,然后设置当前位置为0,也就是从0到limit这块,都写入到同道中
				bf.flip();
				int outlength = 0;
				while ((outlength = outchannel.write(bf)) != 0) {
					System.out.println("读," + length + "写," + outlength);
				}
				// 将当前位置置为0,然后设置limit为容量,也就是从0到limit(容量)这块,
				// 都可以利用,通道读取的数据存储到
				// 0到limit这块
				bf.clear();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fin != null) {
				try {
					fin.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	public static void main(String[] args) {
		//testReadAndWriteNIO();
		//readNIO();
		writeNIO();
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赶路人儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值