这段代码原本目的是扫描是否插入U盘,插入的话,自动将U盘文件全部备份到目标文件夹中。
文件目录是树状结构,很有层次感,且每层操作大致相同。复制目录中的文件,不是创建文件夹操作,就是复制文件操作,所以递归思想在这里很适用。
代码如下:
/****
*
* @author wjw
* @since 2018-02-27
*
*/
public class Copy {
public static void main(String[] args) throws IOException,
InterruptedException {
// 配置文件配置轮询盘符
int second = 10;// 轮询文件是否存在时间间隔
String souPath = "H:/"; // 源路径
String desPath = "E:/U/test"; // 目标路径
File file = new File(souPath);
while (!file.exists()) {
System.out.println(souPath + "目录不存在!");
Thread.sleep(1000 * second);
}
long beginMillis = System.currentTimeMillis();
copy(souPath, desPath);
System.out.println("复制文件约耗时: "
+ (System.currentTimeMillis() - beginMillis) / 1000 + " s.");
}
public static void copy(String souPath, String desPath) throws IOException {
File dir = new File(souPath);
if (dir.isDirectory()) {
System.out.println("开始拷贝目录 " + souPath + " 中的文件到目录 " + desPath
+ " 中...");
String[] filesStr = dir.list();
for (int i = 0; i < filesStr.length; i++) {
String tempSouPath = souPath + File.separator + filesStr[i];
String tempDesPath = desPath + File.separator + filesStr[i];
if (new File(tempSouPath).isDirectory()) {
createDir(tempDesPath);
copy(tempSouPath, tempDesPath);
} else {
copyFile(tempSouPath, tempDesPath);
}
}
System.out.println(souPath + "目录中的文件拷贝完毕!");
} else if (dir.isFile()) {
copyFile(souPath, desPath);
}
}
/****
* 创建目录
*
* @param dirPath
*/
public static void createDir(String dirPath) {
// System.out.println("创建目录:" + dirPath);
File file = new File(dirPath);
if (file != null) {
if (!file.exists()) {
file.mkdir();
}
}
}
/*******
* 复制文件
*
* @throws IOException
*/
public static void copyFile(String sourcePath, String desPath)
throws IOException {
System.out.println(" 开始拷贝文件 " + sourcePath + "...");
FileInputStream fis = null;
FileOutputStream fos = null;
File file = new File(sourcePath);
if (file != null && file.isFile()) {
fis = new FileInputStream(file);
File des = new File(desPath);
fos = new FileOutputStream(des);
int bufferSize = 1024;
byte[] data = new byte[bufferSize];
int length = 0;
while ((length = fis.read(data, 0, bufferSize)) != -1) {
fos.write(data, 0, length);
}
}
fis.close();
fos.close();
System.out.println(" " + desPath + "文件拷贝完毕!");
}
}
如有错误,欢迎指正!
end