需求:实现文件的copy
练习目的:
了解JavaNIO知识,主要是关注一下FileInputStream,FileChannel,FileOutputStream,ByteBuffer 之间的关系
了解如何获取FileChannel
public class CopyFile {
    public static void main(String[] args) throws Exception {
        String inFile = "gitHub.txt";
        String outFile = "gitHub2.txt";
        
        //获取源文件和目标文件的输入流、输出流
        FileInputStream fin = new FileInputStream(inFile);
        FileOutputStream fout = new FileOutputStream(outFile);
        
        //获取输入、输出通道
        FileChannel fcin = fin.getChannel();
        FileChannel fcout = fout.getChannel();
        
        //创建缓存区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        
        while (true) {
        
            //清楚缓存区的数据,可以接收新的数据
            buffer.clear();
        
            //从输入通道中将数据读到缓冲区
            int r = fcin.read(buffer);
        
            //read方法返回读取的字节数,可能为0, 如果该通道已经达到流的末尾,则返回-1
            if (r == -1) {
                break;
            }
        
            //flip方法,让缓冲区可以将新读入的数据写入另一个通道
            buffer.flip();
        
            //从缓存区 将数据写到 输出通道里
            fcout.write(buffer);
        }
        
        //最后关闭
        fcin.close();
        fout.close();
    }
}总结如下:
数据的流向:
什么时候调用FileChannel的read,write方法?
根据数据的方向来确定
    
本文出自 “XEJ分布式工作室” 博客,请务必保留此出处http://xingej.blog.51cto.com/7912529/1968417
原文:http://xingej.blog.51cto.com/7912529/1968417