Java NIO初探

从JDK1.4开始,Java引入了新的IO,在java.nio.*包中。引入新的IO目的在于提高IO的速度。速度的提高主要来自于:“通道和缓冲器”。

与通道直接交互的缓冲器是java.nio.ByteBuffer。

旧的文件IO类库中FileInputStream、FileOutputStream和RandomAccessFile被修改了,可以产生文件通道(FileChannel),但是Reader和Writer这些字符模式类不能产生通道。

下面,我使用NIO写了3个例子,分别是读文件、写文件和文件拷贝:

 

一、写文件

	public void writeFileWithNio(File fileName, String content) throws IOException {
		FileChannel channel = null;
		try {
			channel = new FileOutputStream(fileName).getChannel();
			// 初始化缓冲器,长度为输入字符的字节数
			ByteBuffer temp = ByteBuffer.allocate(content.getBytes("UTF-8").length);
			temp.put(content.getBytes("UTF-8"));
			// 调用此方法为一系列通道写入或相对获取 操作做好准备
			temp.flip();
			channel.write(temp);
			// 强制输出,相当于flush
			channel.force(true);
		} finally {
			if (channel != null && channel.isOpen() == true) channel.close();
		}
	}

 

二、读文件

	public void readFileWithNio(File fileName) throws IOException {
		FileChannel channel = null;
		try {
			channel = new FileInputStream(fileName).getChannel();
			// 初始化缓冲器
			ByteBuffer temp = ByteBuffer.allocate(1024);
			int num = channel.read(temp);
			// 调用此方法为一系列通道写入或相对获取 操作做好准备
			temp.flip();
			byte[] content = new byte[num];
			temp.get(content);
			System.out.println(new String(content,"UTF-8"));
		} finally {
			if (channel != null && channel.isOpen() == true) channel.close();
		}
		
	}
 

三、文件拷贝

	public void copyFileWithNio(File originFile, File targetFile) throws IOException {
		FileChannel inChannel = null;
		FileChannel outChannel = null;
		try {
			inChannel = new FileInputStream(originFile).getChannel();
			outChannel = new FileOutputStream(targetFile).getChannel();
			// 拷贝,从输入通道的第0个开始,到输入通道的总长结束,目的地是输出通道
			inChannel.transferTo(0, inChannel.size(), outChannel);
		} finally {
			if (inChannel != null && inChannel.isOpen() == true) inChannel.close();
			if (outChannel != null && outChannel.isOpen() == true) outChannel.close();
		}
		
	}

 

以上3个都是非常简单的例子,只是用来学习罢了,要运用到实际中是不够的,尤其是读文件那个。

 

另外,旧的IO包实际上也已经使用NIO重新实现过,所以我们即使不使用NIO也可以从中获益的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值