1. 程式人生 > >java如何實現複製檔案

java如何實現複製檔案

package copyfile;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.omg.CORBA.portable.InputStream;

public class copyfile {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		copyfolder("e:/A","e:/B");//將A資料夾複製到B資料夾,B可以是不存在的資料夾
	}

    //複製資料夾
	public static void copyfolder(String sourcefolderName,String destfolderName) {
		File sourcefolder=new File(sourcefolderName);
		if(!sourcefolder.exists()) {
			System.out.println("原檔案必須存在");
			return ;
		}
		File destfolder=new File(destfolderName);
		if(!destfolder.exists()) {
			destfolder.mkdir();
		}
		File[] files=sourcefolder.listFiles();
		for(File file:files) {
			System.out.println(file.getName());
			if(file.isDirectory()) {
				copyfolder(sourcefolder+"/"+file.getName(),
                           destfolderName+"/"+file.getName());
			}
			if(file.isFile()) {
				copyfile(sourcefolder+"/"+file.getName(),
                         destfolderName+"/"+file.getName());
			}
		}
	}
	public static void copyfile(String sourcefile,String destfile) {//複製檔案
		BufferedInputStream bis=null;
		BufferedOutputStream bos=null;
		try {
			bis=new BufferedInputStream(new FileInputStream(new File(sourcefile)));
			bos=new BufferedOutputStream(new FileOutputStream(new File(destfile)));
			byte [] buf=new byte[1024];
			int len=bis.read(buf);
			while(len>0) {
				bos.write(buf,0,len);
				len=bis.read(buf);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			try {
				if(bis!=null)
					bis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if(bos!=null)
					bos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
}