IO programming file copy code


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


 
public class Test1 {
 public static void main (String [] args) throws Exception {
 if (args.length! = 2) {
     System.out.println ("Command execution error, execution structure: java JAVAAPIDEMO Copy source file path Copy target file path");
     System.exit ( 1);
 }
 long start = System.currentTimeMillis ();
 FileUtil fu = new FileUtil (args [0], args [1]);
 
     System.out.println (fu.copy ()? "File copied successfully": "File Copy failed ");
    
 
 long end = System.currentTimeMillis ();
 System.out.println (" Time when copy completed: "+ (end-start));
        
 }
}
 class FileUtil{
     private File srcFile;
     private File desFile;
     public FileUtil(File srcFile,File desFile) {
         this.desFile =desFile;
         this.srcFile =srcFile;
     }
     public FileUtil(String src, String des) {
         this(new File(src),new File(des));
    }
    
    public boolean copy() throws Exception {//文件的拷贝处理
         if(!this.srcFile.exists()) {
            System.out.println("要拷贝的源文件不存在");
             return false;
         }
         if(!this.desFile.getParentFile().exists()) {
             this.desFile.getParentFile().mkdirs();
         }
         byte data[]=new byte[1024];
         InputStream input=null;
         OutputStream out=null;
         try {   input = new FileInputStream(this.srcFile);
                  out = new FileOutputStream(this.desFile);
                  int len=0;
                  while((len=input.read(data))!=-1) {
                      out.write(data,0,len);
                  }
                  
                  
                  
                  
        } catch (Exception e) {
            // TODO: handle exception
        }finally {
            if(input!=null) {
                input.close();
            }if(out!=null) {
                out.close();
            }

        }
        return true;    
    }
 
    
    
    public void copyFileImpl(File srcFile,File desFile) throws Exception {
         byte data[]=new byte[1024];
         InputStream input=null;
         OutputStream out=null;
         try {   input = new FileInputStream(this.srcFile);
                  out = new FileOutputStream(this.desFile);
                  int len=0;
                  while((len=input.read(data))!=-1) {
                      out.write(data,0,len);
                  }
               
                  
        } catch (Exception e) {
            throw e;
        }finally {
            if(input!=null) {
                input.close();
            }if(out!=null) {
                out.close();
            }

        }
    }
    
 }

Guess you like

Origin www.cnblogs.com/yxj808/p/12683396.html