package com.io.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
*
* @author 丢了风筝的线
* @see 文件夹的拷贝
*/
public class Directory {
public static void main(String[] args) {
// 要拷贝的文件夹路径
String originalPath = "D:/新建文件夹/20191014优就业/Java/JavaSECode/day24";
// 目标路径
String targetPath = "C:/Users/Administrator/Desktop";
traversalFile(originalPath, targetPath);
}
public static void traversalFile(String originalPath, String targetPath) {
// 创建原文件操作对象
File originalFile = new File(originalPath);
// 拷贝到那里
targetPath += "/" + originalFile.getName();
System.out.println(targetPath);
// 判断传入的文件路径是文件夹还是文件
if (!originalFile.isDirectory()) {
// 复制文件
Copyfile(originalPath, targetPath);
} else {
// 创建拷贝目录
File targetFile = new File(targetPath);
targetFile.mkdirs();
// 循环遍历原文件中的每个文件夹和文件
File[] files = originalFile.listFiles();
for (File file : files) {
traversalFile(file.getAbsolutePath(), targetPath);
}
}
}
public static void Copyfile(String originalPath, String targetPath) {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
// 输入流对象
inputStream = new FileInputStream(originalPath);
// 输出流对象
outputStream = new FileOutputStream(targetPath);
// 读取文件内容
byte[] flush = new byte[1024];
int len;
while ((len = inputStream.read(flush)) != -1) {
// 写入到目标文件
outputStream.write(flush, 0, len);
// 刷新
outputStream.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭流
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
文件夹的拷贝
最新推荐文章于 2022-12-24 11:45:01 发布