目录拷贝
主要思想是递归,如果遇到文件直接使用IO Stream进行拷贝,调用结束;如果遇到目录就使用File中的list方法进行遍历,重新调用本函数,进行递归。
代码实现了以下两种拷贝方法(拷贝active目录):
1.直接目录拷贝,例如:把"F:\工作\cs自学资料\java\javaSE\ideaPracticeCode\src\com\practice\activate"中的active目录拷贝到"D:\NewDir"目录中。效果为:"D:\NewDir\activate"
2.带有根目录的拷贝(较为复杂),例如:把"F:\工作\cs自学资料\java\javaSE\ideaPracticeCode\src\com\practice\activate"中的active目录拷贝到"D:\NewDir"目录中。效果为:"D:\NewDir\工作\cs自学资料\java\javaSE\ideaPracticeCode\src\com\practice\activate"
方法一:
package com.practice.IO;
import java.io.*;
public class DirectoryCopyTest {
public static void main(String[] args) {
File f1 = new File("F:\\工作\\cs自学资料\\java\\javaSE\\ideaPracticeCode\\src\\com\\practice\\activate");
copyDir(f1.getPath(),"D:\\NewDir");//源路径和目标路径
}
//第一种直接拷贝方式:
public static void copyDir(String o,String n) { //老路径--->新路径
File f1 = new File(o);
if(f1.isFile()){
copy(o,n);
return;
}else if(f1.isDirectory()){
File f2=new File(n+"/"+f1.getName());
if(!f2.exists()){
f2.mkdirs();
}
File[] s1 = f1.listFiles();
for (File f : s1) {
copyDir(f.getPath(),f2.getPath());
}
}
}
public static void copy(String o,String n){
FileInputStream fis=null;
FileOutputStream fos=null;
try {
File f=new File(o);
fis=new FileInputStream(o);
fos=new FileOutputStream(n+"\\"+f.getName());
byte[] b=new byte[4];
int count=0;
while((count=fis.read(b))!=-1){
fos.write(b,0,count);
}
fos.flush();
} 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();
}
}
}
}
}
方法二:
package com.practice.IO;
import java.io.*;
public class DirectoryCopyTest {
public static void main(String[] args) {
File f1 = new File("F:\\工作\\cs自学资料\\java\\javaSE\\ideaPracticeCode\\src\\com\\practice\\activate");
copyDir(f1.getPath(),"D:\\NewDir");
}
//第二种绝对路径方式:
static String dirpath="D:\\NewDir";//这里也要输入目标地址!!!
public static void copyDir(String o,String n) {
File f1 = new File(o);
if(f1.isFile()){
copy(o,n);
return;
}else if(f1.isDirectory()){
String s=(f1.getPath()).substring(3);
File f2=new File(dirpath+"/"+s);
if(!f2.exists()){
f2.mkdirs();
}
File[] s1 = f1.listFiles();
for (File f : s1) {
copyDir(f.getPath(),f2.getPath());
}
}
}
public static void copy(String o,String n){
FileInputStream fis=null;
FileOutputStream fos=null;
try {
File f=new File(o);
fis=new FileInputStream(o);
fos=new FileOutputStream(n+"\\"+f.getName());
byte[] b=new byte[4];
int count=0;
while((count=fis.read(b))!=-1){
fos.write(b,0,count);
}
fos.flush();
} 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();
}
}
}
}
}
写了整整半天(菜鸟入门),个人感觉比网上很多代码都要简洁易用,感兴趣的小伙伴们可以复制代码跑一下试试哦,好用的话别忘了点个赞!