nio是bio的升级版本,能更好的完成文件的输入输出功能,本列子通过FileChannel来完成文件的复制:
public class NIOFileChannelDemo03 { public static void main(String[] args) throws Exception { //输入管道 File file = new File("E:\\file\\1.jpg"); FileInputStream fileInputStream = new FileInputStream(file); FileChannel inChannel = fileInputStream.getChannel(); //输出管道 FileOutputStream fileOutputStream = new FileOutputStream("E:\\file\\2.jpg"); FileChannel outChannel = fileOutputStream.getChannel(); //创建缓冲区 ByteBuffer byteBuffer = ByteBuffer.allocate((int)file.length()); //数据读取到缓冲区 inChannel.read(byteBuffer); byteBuffer.flip(); //数据写入到缓冲区 outChannel.write(byteBuffer); System.out.println("复制完成..."); //关闭管道和缓冲区 outChannel.close(); fileOutputStream.close(); inChannel.close(); fileInputStream.close(); } } |