用javaI/O流来拷贝目录及目录中所有文件

package org.tarena.day02;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class BufferedInputStreamDemo {
static String path;
public static void copyDir(File fromDir, File toDir) throws Exception {
	toDir.mkdir();// 目标目录创建出来;
	File[] files = fromDir.listFiles();
	if (files == null)return;
	for (File file : files) {
	path = toDir.getPath() + "/" + file.getName();
	//创建目标文件或目录的路径;
	if (file.isDirectory()) {
	    copyDir(file, new File(path));//递归创建源目录中与目标位置相应的目录;
	} else {
	    BufferedInputStream bis = new BufferedInputStream(
		new FileInputStream(file));
		System.out.println(path);
		BufferedOutputStream bos = new BufferedOutputStream(
		new FileOutputStream(new File(path)));
		byte[] buf = new byte[1024];
		while (bis.read(buf) != -1) {
//注意一点要把读到的内容放到buf数组中,否则bos.write(buf)是取不到字符值的;
		    bos.write(buf);
		}
		    bis.close();
		    bos.close();
		}
	}
}

public static void main(String[] args) {
	File one = new File("/home/soft22/Desktop/232");//源文件;
	File two = new File("/home/soft22/Desktop/aaa");//目标文件;
	try {
		copyDir(one, two);
		System.out.println("文件copy成功!!!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


你可能感兴趣的:(java)