使用I/O流拷贝文件夹
import java.io.*;
public class test{
public static void main(String[] args) {
test test = new test();
String s = test.fileCopy("D:/", "E:/d");
System.out.println(s);
}
public String fileCopy(String path,String pathcopy){
File f1 = new File(path);
File f2 = new File(pathcopy);
if (!f2.isDirectory()){
return "请输入需要存放的文件夹";
}
if (f1.isFile()){
pathcopy = pathcopy+"/"+f1.getName();
if (this.filecopyff(path,pathcopy)) {
return "拷贝成功";
}else {
return "拷贝失败";
}
}else if (f1.isDirectory()){
pathcopy = pathcopy+"/"+f1.getName();
if (this.directoryCopy(path,pathcopy)) {
return "拷贝成功";
}else {
return "拷贝失败";
}
}else {
return "请输入文件或文件夹";
}
}
public boolean filecopyff(String path,String pathcopy){
System.out.println(path+"==>"+pathcopy);
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(path);
fos = new FileOutputStream(pathcopy);
byte[] bytes = new byte[1024];
int a;
while ((a = fis.read(bytes)) != -1) {
fos.write(bytes);
}
fos.flush();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fos.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
public boolean directoryCopy(String path,String pathcopy){
File f1 = new File(path);
File[] files = f1.listFiles();
File f2 = new File(pathcopy);
if (!f2.exists()){
f2.mkdir();
}
String oldPath;
String newPath;
for (File file : files) {
if (file.isFile()){
oldPath = path+"/"+file.getName();
newPath = pathcopy+"/"+file.getName();
this.filecopyff(oldPath,newPath);
}else {
oldPath = path+"/"+file.getName();
newPath = pathcopy+"/"+file.getName();
this.directoryCopy(oldPath,newPath);
}
}
return true;
}
}