本程序可以复制文件,或者文件夹
用到io和递归的知识:
复制文件夹,要层层深入,因为文件夹中可能含有文件夹,复制时,要先创建这个新文件夹,所以要拼接路径.思路清楚即可
代码如下:
package com.carlinfo.filetree;
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;
public class CopyFolder2 {
public static void main(String[] args) {
/* 准备源路径 */
String path = "H:\\test2";
File sourceFile = new File(path);
/* 目标路径 */
String path2 = "h:\\test\\c";
File TargetFile = new File(path2);
copy(sourceFile, TargetFile);
System.out.println("复制成功!");
}
public static void copy(File sourceFile, File TarFile) {
String str = "";
/* 判断该文件是不是文件夹,是文件,直接复制文件 */
if (!sourceFile.isDirectory()) {
cy(sourceFile, TarFile);
} else {
str = TarFile.getPath() + "\\" + sourceFile.getName();
System.out.println("--创建文件夹-->" + str);
File fs = new File(str);
fs.mkdir();
/* 将该文件夹中的文件取出来 */
File[] listFiles = sourceFile.listFiles();
for (int i = 0; i < listFiles.length; i++) {
/* 对文件夹遍历,判断是文件还是文件夹 */
if (!listFiles[i].isDirectory()) {
cy(listFiles[i], fs);
} else {
/* 如果是文件夹,继续调自己,递归 */
copy(listFiles[i], fs);
}
}
}
}
/**
* 复制文件
* 用到io字节流
*
* @param sourceFile
* @param TarFile
*/
public static void cy(File sourceFile, File TarFile) {
/* 用于拼装路径,因为目标文件不存在 */
String str = "";
/* 准备管子 */
FileInputStream fis = null;
FileOutputStream fos = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
/* 准备容器 */
byte[] b = new byte[1024];
/* 拼装路径 */
str = TarFile.getPath() + "\\" + sourceFile.getName();
System.out.println("--创建文件--" + str);
File file = new File(str);
try {
file.createNewFile();
fis = new FileInputStream(sourceFile);
bis = new BufferedInputStream(fis);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
int len = 0;
while ((len = bis.read(b)) != -1) {
/* 写数据 */
bos.write(b, 0, len);
}
bos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
/* 记得关闭管子 */
bis.close();
bis = null;
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (bos != null) {
/* 关闭管子 */
bos.close();
bos = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}