【JAVA】编程(6)--- 应用IO流拷贝文件夹(内含多个文件)到指定位置

此程序应用了:

File 类,及其常用方法;

FileInputStream,FileOutputStream类及其常用方法;

递归思维;


package com.bjpowernode.javase.io;
import java.io.*;
public class IOTest {
public static void main(String[] args) {
//拷贝源路径:...\\pra\\...
File srcFile=new File("C:\\java-prictice\\javaseplus\\pra");
//拷贝目标:...\\c\\...
File destFile=new File("C:\\a\\b\\c");
//若拷贝目标路径不存在,创建多级文件夹
if (!destFile.exists()){
destFile.mkdirs();
}
//调用拷贝方法
copyDir(srcFile,destFile);
}
private static void copyDir(File srcFile,File destFile){
//声明空指针引用
FileInputStream fis=null;
FileOutputStream fos=null;
//递归的结束条件(拷贝源是文件,没有子文件了)
if (srcFile.isFile()){
try {
//字节输入流绑定拷贝源,字节输出流绑定拷贝目标
fis=new FileInputStream(srcFile);
//获取不包含上级路径的文件名
String scrDir=srcFile.getName();
//在拷贝目标的路径后 + “\\拷贝源的文件名”(不包含上级路径)
fos=new FileOutputStream(destFile.getAbsolutePath().endsWith("\\")?destFile.getAbsolutePath():(destFile.getAbsolutePath()+"\\"+scrDir));
//一次最多读取1MB
byte [] bytes=new byte[1024*1024];
int readCound;
//文件拷贝完成
while ((readCound=fis.read(bytes))!=-1){
fos.write(bytes);
}
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return;
}
//能到这说明是文件夹,获取文件夹下的所有子文件
File [] files=srcFile.listFiles();
for (File file:files) {
//子文件若是文件夹,则新建此文件夹
if (file.isDirectory()){
String srcDir=file.getAbsolutePath();
String destDir=(destFile.getAbsolutePath().endsWith("\\")?destFile.getAbsolutePath():destFile.getAbsolutePath()+"\\"+srcDir.substring(3));
File newFile=new File(destDir);
}
//递归
copyDir(file,destFile);
}
}
}

效果展示:


运行前:

【JAVA】编程(6)--- 应用IO流拷贝文件夹(内含多个文件)到指定位置

运行后:

【JAVA】编程(6)--- 应用IO流拷贝文件夹(内含多个文件)到指定位置

心得:


递归方法中的  copyDir ( file , destFile ) ; // 内部执行的拷贝顺序:

/*拷贝顺序:
1.pra的第一个子文件夹(若是文件则进行pra下一个子文件的拷贝)
2.上一个子文件夹的第一个子文件夹(若是文件则返回步骤1)
3.上一个子文件夹的第一个子文件夹(若是文件则返回步骤2)
......
n.上一个子文件夹的第一个子文件夹(若是文件则返回步骤“n-1”)
最后,pra的最后一个子文件拷贝完成/
pra的最后一个子文件夹中的最后一个文件拷贝完成/
pra的最后一个子文件夹的最后一个文件夹的最后一个文件拷贝完成!
所有递归方法结束,copyDir方法结束
*/
上一篇:费用流 ZOJ 3933 Team Formation


下一篇:PHP中 magic_quotes_gpc 和 magic_quotes_runtime 区别及其反斜线转义问题