java实现文件夹拷贝,拷贝文件夹及文件夹下所有的文件(和windows的拷贝功能一致),自己边学习边写的,上代码
拷贝类CopyDir.java代码:
package com.cb.homework;
import java.io.*;
public class CopyDir {
/**
* 先创建顶级目录
* @param source
* @param aid
*/
public void copyDir(String source, String aid)
{
File sourDir = new File(source);
File aidDir = new File(aid);
if (!sourDir.isDirectory() || !aidDir.isDirectory())
{
System.out.println("传入参数不对,应该传入两个文件夹的路径");
return;
}
File aidDirLast = new File(aid + "\\" + sourDir.getName());
if (!aidDirLast.exists())
{
aidDirLast.mkdir();
}
copyDirFiles(source, aidDirLast.getAbsolutePath());
}
/**
* 拷贝目录
* @param source 原目录文件路径
* @param aid 现拷贝路径
*/
private void copyDirFiles(String source, String aid) {
System.out.println("源文件目录:" + source + "拷贝到:" + aid);
File sourDir = new File(source);
File [] fileList = sourDir.listFiles();
for (File file:fileList) {
if (file.isFile())
{
// 拷贝
copyFile(file.getAbsolutePath(), aid + "\\" + file.getName());
}else if(file.isDirectory())
{
// 创建目录,递归
String aidTemp = aid + "\\" + file.getName();
//System.out.println(aidTemp);
File tempAid = new File(aidTemp);
if (!tempAid.exists())
{
tempAid.mkdir();
}
// 继续遍历
copyDirFiles(file.getAbsolutePath(), aidTemp);
}
}
}
/**
* 拷贝文件
* @param sourceFile 源文件
* @param aidFile 目标文件
*/
private void copyFile(String sourceFile, String aidFile){
FileInputStream fi = null;
FileOutputStream fo = null;
try {
fi = new FileInputStream(sourceFile);
fo = new FileOutputStream(aidFile);
byte[] bytes = new byte[1024*1024];
int readData = 0;
while ((readData = fi.read(bytes)) != -1)
{
fo.write(bytes, 0 , readData);
}
fo.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (null != fi)
{
try {
fi.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != fo)
{
try {
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
测试代码:
package com.cb.homework;
public class MianTest {
public static void main(String[] args) {
CopyDir copyDir = new CopyDir();
copyDir.copyDir("E:\\phpstudy_pro","C:");
}
}
有写的不对的地方欢迎各位指点一二
本文详细介绍了如何使用Java编写CopyDir类,实现在Windows风格下复制文件夹及其所有内容的功能,包括创建目标目录、递归处理子文件夹和文件。通过MianTest测试示例展示了整个过程。
2881

被折叠的 条评论
为什么被折叠?



