java怎样实现文件拷贝?

解决方案 »

  1.   

    给你个源程序:import java.io.*;public class FileCopy {
      public static void main(String[] args) {
        if (args.length!=2)                    //检测程序是否有两个参数
          System.err.println("Usage: java FileCopy <source> <destination>");
        else {
          try { copy(args[0],args[1]); }
          catch(IOException e) { System.err.println(e.getMessage()); }
        }
      }  public static void copy(String from_name,String to_name) throws IOException {
        File from_file=new File(from_name);             //获取file对象
        File to_file=new File(to_name);    if(!from_file.exists())                         //确定原文件是否存在
          abort("no such source file: "+from_name);
        if(!from_file.isFile())                         //确定是否是一个文件
          abort("can't copy directory: "+from_name);
        if(!from_file.canRead())                        //确定文件是否可读
          abort("source file is unreadable: "+from_name);    if(to_file.isDirectory())                       //如果目标是目录,将原文件名做为目标文件名
          to_file=new File(to_file,from_file.getName());   //既将该目录的名称用做目标文件的名称    if(to_file.exists()) {
          if(!to_file.canWrite())                       //如果目标存在,确定是否可写
            abort("destination file is unwriteable: "+to_name);
          System.out.print("Overwrite existing file "+to_file.getName()+"?(Y/N):"); //如果可写,确定是否可以覆盖
          System.out.flush();
          BufferedReader in=new BufferedReader(new InputStreamReader(System.in));  //获取用户响应
          String response=in.readLine();
          if(!response.equals("Y")&&!response.equals("y"))     //如果是yes,放弃复制
            abort("existing file was not overwritten.");
        }
        else {                                          //如果文件不存在,检测目录是否存在,是否可写
           String parent=to_file.getParent();      //目标目录
           if(parent==null)                            //如果getParent返回null,则目录是当前目录
              parent=System.getProperty("user.dir");
           File dir=new File(parent);                 //并将目录转换成文件
           if(!dir.exists())
              abort("destination directory doesn't exist: "+parent);
           if(dir.isFile())
              abort("destination is not a directory: "+parent);
           if(!dir.canWrite())
              abort("destination directory is unwriteable: "+parent);
        }
                                                           //到此说明一切正常
        FileInputStream from=null;                         //置源流
        FileOutputStream to=null;                          //置目标流
        try {
          from=new FileInputStream(from_file);       //创建输入流
          to=new FileOutputStream(to_file);          //创建输出流
          byte[] buffer=new byte[4096];              //保存文件内容到buffer
          int bytes_read;                            //缓冲区大小
          while((bytes_read=from.read(buffer))!=-1)  //读直到文件末尾
            to.write(buffer,0,bytes_read);           //写入buffer
        }
        finally {                                    //关闭流(永远不要忘记)
          if(from!=null) try { from.close(); } catch(IOException e) { ; }
          if(to!=null) try { to.close(); } catch(IOException e) { ; }
        }
      }  private static void abort(String msg) throws IOException {   //异常抛出的简单程序
        throw new IOException("FileCopy: "+msg);
      }
    }
      

  2.   

    我建议你仔细看一下这片文章!!http://developer.java.sun.com/developer/JDCTechTips/2002/tt0507.html#tip1比如:    import java.nio.*;
        import java.nio.channels.*;
        import java.io.*;
       
        public class ChannelDemo {
            public static void main(String args[])
                                       throws IOException {
       
                // check command-line arguments
       
                if (args.length != 2) {
                    System.err.println("missing filenames");
                    System.exit(1);
                }
       
                // get channels
       
                FileInputStream fis =
                              new FileInputStream(args[0]);
                FileOutputStream fos =
                             new FileOutputStream(args[1]);
                FileChannel fcin = fis.getChannel();
                FileChannel fcout = fos.getChannel();
       
                // do the file copy
       
                fcin.transferTo(0, fcin.size(), fcout);
       
                // finish up
       
                fcin.close();
                fcout.close();
                fis.close();
                fos.close();
            }
        }
      

  3.   

    File类并不仅仅是对现有目录路径、文件或者文件组的一个表示。亦可用一个File对象新建一个目录,甚至创建一个完整的目录路径——假如它尚不存在的话。亦可用它了解文件的属性(长度、上一次修改日期、读/写属性等),检查一个File对象到底代表一个文件还是一个目录,以及删除一个文件等等。下列程序完整展示了如何运用File类剩下的这些方法://: MakeDirectories.java
    // Demonstrates the use of the File class to
    // create directories and manipulate files.
    import java.io.*;public class MakeDirectories {
      private final static String usage =
        "Usage:MakeDirectories path1 ...\n" +
        "Creates each path\n" +
        "Usage:MakeDirectories -d path1 ...\n" +
        "Deletes each path\n" +
        "Usage:MakeDirectories -r path1 path2\n" +
        "Renames from path1 to path2\n";
      private static void usage() {
        System.err.println(usage);
        System.exit(1);
      }
      private static void fileData(File f) {
        System.out.println(
          "Absolute path: " + f.getAbsolutePath() +
          "\n Can read: " + f.canRead() +
          "\n Can write: " + f.canWrite() +
          "\n getName: " + f.getName() +
          "\n getParent: " + f.getParent() +
          "\n getPath: " + f.getPath() +
          "\n length: " + f.length() +
          "\n lastModified: " + f.lastModified());
        if(f.isFile())
          System.out.println("it's a file");
        else if(f.isDirectory())0D
          System.out.println("it's a directory");
      }
      public static void main(String[] args) {
        if(args.length < 1) usage();
        if(args[0].equals("-r")) {
          if(args.length != 3) usage();
          File 
            old = new File(args[1]),
            rname = new File(args[2]);
          old.renameTo(rname);
    0A      fileData(old);
          fileData(rname);
          return; // Exit main
    0A    }
        int count = 0;
        boolean del = false;
        if(args[0].equals("-d")) {
          count++;
          del = true;
        }
        for( ; count < args.length; count++) {
          File f = new File(args[count]);
          if(f.exists()) {
            System.out.println(f 2B " exists");
            if(del) {
              System.out.println("deleting..." + f);
              f.delete();
            }
          } 
          else { // Doesn't exist0D
            if(!del) {
              f.mkdirs();
              System.out.println("created " + f);
            }
          }
          fileData(f);
        }  
      }
    } ///:~在fileData()中,可看到应用了各种文件调查方法来显示与文件或目录路径有关的信息。
    main()应用的第一个方法是renameTo(),利用它可以重命名(或移动)一个文件至一个全新的路径(该路径由参数决定),它属于另一个File对象。这也适用于任何长度的目录。
    若试验上述程序,就可发现自己能制作任意复杂程度的一个目录路径,因为mkdirs()会帮我们完成所有工作。==============================
    在下所说,也许并非正确,请从建议的角度
      

  4.   

    一点补充,关于性能上的优化
        /**
         *  文件拷贝。
         *
         *@param  from             源路径。
         *@param  to               目标路径。
         *@exception  IOException  Description of the Exception0D
         */
        public static void copy( String from, String to )
                         throws IOException
        {
            int BUFF_SIZE = 100000;
            byte[] buffer = new byte[ BUFF_SIZE ];
            InputStream in = null;
            OutputStream out = null;        try
            {
                in = new FileInputStream( from );0D
                out = new FileOutputStream( to );0D            while ( true )
                {
                    synchronized ( buffer )
                    {
                        int amountRead = in.read( buffer );                    if ( amountRead == -1 )
                        {
                            break;
                        }                    out.write( buffer, 0, amountRead );
    0A                }
                }
            }
            finally
            {
                if ( in != null )
                {
                    in.close();
                }            if ( out != null )
                {
                    out.close();0D
                }
            }
        }
    ================================================================
    Someone
      

  5.   

    使用java.io包里的FileInputStream类和FileOutputStream类。自个去查查API文档吧