写了好久,来一个备注详细的版本吧
1.把 “E:\itcast”(单级文件夹)这个文件夹复制到模块目录下:
public class CopyFolderDemo {
public static void main(String[] args) throws IOException {
//创建数据源目录File对象,路径是E:\\itcast
File srcFolder = new File("E:\\itcast");
//获取数据源目录File对象的名称(itcast)
String srcFolderName = srcFolder.getName();
//创建目的地目录File对象,路径名是模块名+itcast组成(myCharStream\\itcast)
File destFolder = new File("myCharStream",srcFolderName);
//判断目的地目录对应的File是否存在,如果不存在,就创建
if(!destFolder.exists()) {
destFolder.mkdir();
}
//获取数据源目录下所有文件的File数组
File[] listFiles = srcFolder.listFiles();
//遍历File数组,得到每一个File对象,该File对象,其实就是数据源文件
for(File srcFile : listFiles) {
//数据源文件:E:\\itcast\\mn.jpg
//获取数据源文件File对象的名称(mn.jpg)
String srcFileName = srcFile.getName();
//创建目的地文件File对象,路径名是目的地目录+mn.jpg组成
(myCharStream\\itcast\\mn.jpg)
File destFile = new File(destFolder,srcFileName);
//复制文件
copyFile(srcFile,destFile);
}
}
private static void copyFile(File srcFile, File destFile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new
FileInputStream(srcFile));
BufferedOutputStream bos = new BufferedOutputStream(new
FileOutputStream(destFile));
byte[] bys = new byte[1024];
int len;
while ((len=bis.read(bys))!=-1) {
bos.write(bys,0,len);
}
bos.close();
bis.close();
}
}
2.把 “E:\itcast”(多级文件夹)这个文件夹复制到 F盘目录下:
public class CopyFoldersDemo {
public static void main(String[] args) throws IOException {
//创建数据源File对象,路径是E:\\itcast
File srcFile = new File("E:\\itcast");
//创建目的地File对象,路径是F:\\
File destFile = new File("F:\\");
//写方法实现文件夹的复制,参数为数据源File对象和目的地File对象
copyFolder(srcFile,destFile);
}
//复制文件夹
private static void copyFolder(File srcFile, File destFile) throws IOException
{
//判断数据源File是否是目录
if(srcFile.isDirectory()) {
//在目的地下创建和数据源File名称一样的目录
String srcFileName = srcFile.getName();
File newFolder = new File(destFile,srcFileName); //F:\\itcast
if(!newFolder.exists()) {
newFolder.mkdir();
}
//获取数据源File下所有文件或者目录的File数组
File[] fileArray = srcFile.listFiles();
//遍历该File数组,得到每一个File对象
for(File file : fileArray) {
//把该File作为数据源File对象,递归调用复制文件夹的方法
copyFolder(file,newFolder);
}
} else {
//说明是文件,直接复制,用字节流
File newFile = new File(destFile,srcFile.getName());
copyFile(srcFile,newFile);
}
}
//字节缓冲流复制文件
private static void copyFile(File srcFile, File destFile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new
FileInputStream(srcFile));
BufferedOutputStream bos = new BufferedOutputStream(new
FileOutputStream(destFile));
byte[] bys = new byte[1024];
int len;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
bos.close();
bis.close();
}
}