用递归来写,我刚写的不太简便但是功能实现了
package com.itheima;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Filecopypath {
private static InputStream ips;
private static OutputStream ops;
public static void main(String[] args) throws FileNotFoundException {
File fileyuan = new File("D:\\你字啊");
File filemd = new File("D:\\新建文件夹 (2)");
copy(fileyuan,filemd);
}
private static void copy(File fileyuan, File filemd) throws FileNotFoundException {
// TODO Auto-generated method stub
//把源中的所有文件路径记录下来
File[] files = fileyuan.listFiles();
//遍历所有路径
for(int i=0; i<files.length;i++){
// /路径为目录就执行下面的递归
if(files[i].isDirectory()){
// System.out.println(files[i]);
int in = files[i].toString().lastIndexOf("\\");
String name = files[i].toString().substring(in, files[i].toString().length());
File f = new File(filemd+name);
f.mkdir();
System.out.println(f);
copy(files[i],f);
}
//在判断一下路径不是目录那么就把该文件输出到目的里
if(!(files[i].isDirectory())){
ips = new FileInputStream(files[i]);
int in = files[i].toString().lastIndexOf("\\");
String filename = files[i].toString().substring(in, files[i].toString().length());
ops = new FileOutputStream(filemd+filename);
byte[] by = new byte[1024];
int len=0;
try {
while((len = ips.read(by))!=-1){
ops.write(by);
ops.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
|