【Java日常练习题】拷贝目录
拷贝目录:
将E:javajavacode拷贝到D盘根目录下
需要用到:
1. FileInputStream
2. FileOutputStream
3. File
思路:
一、 先定义拷贝源和拷贝目标
二、编写拷贝方法:
- 获取源下面的子目录
- 通过 forEach循环,方法递归,在目标处创建对应的目录,当srcFile是一个文件时,递归结束
- 且当srcFile是一个文件时,开始一边读一边写
代码实现:
import java.io.*;
public class CopyAll {
public static void main(String[] args) {
// 拷贝源
File srcFile = new File("E:\java\javacode");
// 拷贝目标
File destFile = new File("D:\");
// 调用拷贝方法
copyDir(srcFile,destFile);
}
private static void copyDir(File srcFile, File destFile) {
if (srcFile.isFile()){
//srcFile如果是一个文件,递归结束
// 是文件的时候需要拷贝
// ...一边读一遍写
FileInputStream in = null;
FileOutputStream out = null;
try {
// 读这个文件
// E:javajavacode.settingsorg.eclipse.jdt.core.prefs
in = new FileInputStream(srcFile);
// 写到这个文件中
// D:javajavacode.settingsorg.eclipse.jdt.core.prefs
String path = (destFile.getAbsolutePath().endsWith("\")? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\" ) +srcFile.getAbsolutePath().substring(3);
out = new FileOutputStream(path);
// 一边读一边写
// 一次拷贝1MB
byte [] bytes = new byte[1024*1024];
int readCount = 0;
while ((readCount = in.read(bytes)) !=-1){
out.write(bytes,0,readCount);
}
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if ( out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return;
}
// 获取源下面的子目录
File [] files = srcFile.listFiles();
for (File file : files){
// 获取所有文件(包括文件和目录)的绝对路径
//System.out.println(file.getAbsolutePath());
if (file.isDirectory()){
// 新建对应的目录
//System.out.println(file.getAbsolutePath());
String srcDir = file.getAbsolutePath();
String destDir = (destFile.getAbsolutePath().endsWith("\")? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\" )+ srcDir.substring(3);
File newFile = new File(destDir);
if (!newFile.exists()){
newFile.mkdirs();
}
}
// 递归调用
copyDir(file,destFile);
}
}
}
