从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也可以从中获益的。