说明:当我在学习IO流的时候,发现FileInputStream文件专属流在定义的时候里面的属性可以是File类型的,例如FileInputStream(File file) ,但是我不知道File是什么东西,经过我的查询发现,File原来有这样的用处:
回归正题,开始把标题中的代码实现,里面使用到的大多数方法都在上面的图片中;
代码如下:
public class Test {
// 存储“C:\data”文件的绝对路径长度,等会复制里面文件的时候需要去掉这个长度
private static int length;
public static void main(String[] args) {
// 被复制的文件夹路径
File fromFile = new File("C:\\data");
// length就是"C:\data"的长度
length = fromFile.getParentFile().getAbsolutePath().length();
// 复制到哪个路径
File toFile = new File("C:\\test\\copy");
// 复制函数
copyDir(fromFile, toFile);
// 提示复制完成
System.out.println("复制完成");
}
/**
* 复制方法
*
* @param fromFile 被复制的文件
* @param toFile 目标文件
*/
private static void copyDir(File fromFile, File toFile) {
if (fromFile.isFile()) {
// 1、如果是文件,说明不需要往下复制了,已经到底了
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = new FileInputStream(fromFile);
// 被赋值文件的绝对路径
String fromFilePath = fromFile.getAbsolutePath();
// 在目标目录中的绝对路径
String toFilePath = toFile.getAbsolutePath() + fromFilePath.substring(length);
// 写到目标目录中的绝对路径里面
outputStream = new FileOutputStream(toFilePath);
// bytes代表1G
byte[] bytes = new byte[1024 * 1024];
int count = 0;
while ((count = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, count);
}
// 防止管道中有遗留
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭IO流
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
// 2、如果是文件夹,那么就获得文件夹下面所有的文件
// 如果文件是目录的话,那就先生成空目录
String path = toFile.getAbsolutePath() + fromFile.getAbsolutePath().substring(length);
File myFile = new File(path);
// 判断是否存在,如果存在就不生成了,否则就生成目录
if (!myFile.exists()) {
myFile.mkdirs();
}
File[] files = fromFile.listFiles();
// 如果文件夹是个空文件夹,那就不做操作了
if (files != null && files.length > 0) {
for (File file : files) {
// 使用递归生成所有的文件
copyDir(file, toFile);
}
}
}
}
}