嘿牛程序员__成都传智博客__文件的拷贝:单个文件的拷贝(下)

来源:互联网 发布:数据自动传输的风速仪 编辑:程序博客网 时间:2024/06/12 21:11

---------------------- android培训、java培训、期待与您交流! ----------------------

微笑本节继续研究单个文件的拷贝
前面我们主要采用了两种方法,一种是通过字节流,一种是被包装称字符流。那么我们是否可以选取一种整体移动的方法,于是我们就想到了通道。
下面我们主要通过通道FileChannel,以及方法getChannel()、transferFrom(),来实现文件的拷贝
//实现如下
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.io.*;
public class FoundationTest1
{

 /**
  *编写程序拷贝一个文件. 尽量使用效率高的方式。
  */
 public static void main(String[] args)
 {
 if(args.length<2)
    {
            System.out.println("参数不够,请输入两个参数");
    }
    else
     if(args.length >2)
        {
            System.out.println("参数太多,请输入两个参数");
        }
     else
        {
            copyFile(args[0],args[1]);//java FoundatiinTest1 d:\1.txt e:\1.txt
        }
   
 
 }
        /**
  *FileChannel 用于读取、写入、映射和操作文件的通道。
         *文件中的某个区域直接映射到内存中;对于较大的文件,这通常比调用普通的 read 或 write 方法更为高效。
  */
 private static void copyFile(String str1,String str2)
 {
    File file1=new File(str1);
    File file2=new File(str2);
    try
    {
    FileInputStream fis = new FileInputStream(file1);
    FileOutputStream fos = new FileOutputStream(file2);
    FileChannel fc1 = fis.getChannel();
    FileChannel fc2 = fos.getChannel();
    fc2.transferFrom(fc1, 0, fc1.size());
    fc1.close();
    fc2.close();
    fis.close();
    fos.close(); 
    }
    catch(FileNotFoundException e)
    {
     e.printStackTrace();
    }
    catch (IOException e)
    {
   e.printStackTrace();
    }
   
 }
 
}

再见

---------------------- android培训、java培训、期待与您交流! ----------------------详细请查看:http://edu.csdn.net/heima

原创粉丝点击