对于io操作我们并不陌生,常见的文件处理流程都有IO操作。
先来了解一下NIO。NIO就是多路复用的IO,它主要是由selector,channel和buffer组成,selector可以叫做多路复用选择器,channel是传输数据的管道,buffer是存储数据的缓冲区。下面的图表示的是这三者之间的关系。
一个selector可以监听多个Channel。
Channel和IO中的stream是一个等级的,例如inputStream,outputStream,不同的是stream是单向的 ,Channel是双向的,它既可以进行读操作也能进行写操作。常见的channel有一下几种,SocketChannel,ServerSocketChannel,DatagramChannel和FileChannel。
Buffer就是一个存放数据的容器,是一个连续的数组。在NIO中buffer是一个顶层的父类,它的子类主要有ByteBuffer、IntBuffer、 CharBuffer、 LongBuffer、 DoubleBuffer、FloatBuffer,ShortBuffer。
我们用代码来实现一下NIO的文件操作(transferTo):
public static void fileChannelCopy(String sfPath, String tfPath) {
File sf = new File(sfPath);
File tf = new File(tfPath);
FileInputStream fi = null;
FileOutputStream fo = null;
FileChannel in = null;
FileChannel out = null;
try{
fi = new FileInputStream(sf);
fo = new FileOutputStream(tf);
in = fi.getChannel();//得到对应的文件通道
out = fo.getChannel();//得到对应的文件通道
in.transferTo(0, in.size(), out);
}catch (Exception e){
e.printStackTrace();
}finally {
try{
fi.close();
in.close();
fo.close();
out.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
再看下传统io的文件复制操作:
private static void traditionalCopy(String sourcePath, String destPath) throws Exception {
File source = new File(sourcePath);
File dest = new File(destPath);
if (!dest.exists()) {
dest.createNewFile();
}
FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int len = 0;
while ((len = fis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
}