io流文件夹及文件复制,出现文件夹子文件和文件夹同在一个目录

weixin_50996685 weixin_50996685 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
import java.io.*;

public class FileDirTest01 {
public static void main(String[] args) {
// 拷贝文件夹目录
File in = new File("");
// 拷贝目标(目录)
File out = new File("");
// 调用方法
CopyDir(in, out);
}

/**
* 拷贝文件夹里面文件夹及文件,
* @param in 拷贝文件目录
* @param out 拷贝目标(目录)
*/
private static void CopyDir(File in, File out) {
if(in.isFile()) {
// srcFile如果是一个文件的话,递归结束。
// 是文件的时候需要拷贝。
// ....一边读一边写。
FileInputStream input = null;
FileOutputStream output = null;
try {
// 读这个文件
input = new FileInputStream(in);
// 写文件到新的目录为 out.getAbsolutePath()+"\\"+in.getName()
output = new FileOutputStream(out.getAbsolutePath()+"/"+in.getName());
byte[] bytes = new byte[1024*1024]; //一次复制1M
int readCount = 0;
/**
* 复制文件 一次复制1024*1024字节(1M)
*/
while((readCount = input.read(bytes)) != -1) {
output.write(bytes,0,readCount);
}
output.flush();

} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return;
}
File[] files = in.listFiles();
for (File file: files) {
if (file.isDirectory()) { //判断是否为文件夹,是
// 新的目录为 out.getAbsolutePath() + "/" + in.getName()
File newDir = new File(out.getAbsolutePath()+"\\"+in.getName());
if (!newDir.exists()) { //判断是否含有此文件夹,否
newDir.mkdirs(); //创建子目录
}
CopyDir(file,newDir);
System.out.println(newDir.getAbsolutePath());
System.out.println(file.getAbsolutePath());
}
// 递归方法CopyDir
CopyDir(file,out);
}
}
}
...全文

相关推荐

评论 2
收藏 已收藏
分享
返回顶部
weixin_50996685
Java SE 62,621 成员 307,251 内容