代码如下(示例):
import java.io.*;
public class DirectoryCopy {
public static void main(String[] ages){
//源目录
File stateFile = new File("E:\\王志海老师大三下学期");
//目标目录
File destFile = new File("D:\\");
//调用拷贝方法
CopyDis(stateFile,destFile);
}
private static void CopyDis(File stateFile, File destFile) {
if(stateFile.isFile()){//如果是源目录是文件
//创建流文件
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(stateFile);
//获取目标文件的路径
String strDest = (destFile.getAbsolutePath().endsWith("\\")
? destFile.getAbsolutePath()
: destFile.getAbsolutePath()+"\\")//判断目标路径最后一位是否是“\\”结尾
+stateFile.getAbsolutePath().substring(3);//获得源目录地址的第三位以后的地址
fos = new FileOutputStream(strDest);
//开始边读边写
byte[] bytes = new byte[1024*1024];
int readCount = 0;
while((readCount = fis.read(bytes)) != -1){
fos.write(bytes,0,readCount);
}
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return;
}
//如果源目录不是文件,将运行到这里
File[] files = stateFile.listFiles();
for (File file : files){
if(file.isDirectory()){//判断是否是目录
String srcDir = file.getAbsolutePath();
String dirDest = (destFile.getAbsolutePath().endsWith("\\")
? destFile.getAbsolutePath()
: destFile.getAbsolutePath()+"\\")
+srcDir.substring(3);
File dirFIle = new File(dirDest);
if (!dirFIle.exists()){//判断文件是否存在
dirFIle.mkdirs();
}
}
CopyDis(file,destFile);
}
}
}