因为需要一个xcopy复制目录树,写了这个测试代码。记得有参考网上代码,但时间太久找不到参考来源了。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class xcopy{
// 递归方法
public static void copyFile(File file, File file2) {
// 当找到目录时,创建目录
if (file.isDirectory()) {
print("dir:"+file.getName()+","+file2.getName());
file2.mkdir();
File[] files = file.listFiles();
for (File file3 : files) {
// 递归
copyFile(file3, new File(file2, file3.getName()));
}
//当找到文件时
} else if (file.isFile()) {
print("file:"+file.getName());
File file3 = new File(file2.getAbsolutePath());
try {
file3.createNewFile();
copyDatas(file.getAbsolutePath(), file3.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 复制文件数据的方法
public static void copyDatas(String filePath, String filePath1) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
// 字节流
fis = new FileInputStream(filePath);
fos = new FileOutputStream(filePath1);
byte[] buffer = new byte[1024];
while (true) {
int temp = fis.read(buffer, 0, buffer.length);
if (temp == -1) {
break;
} else {
fos.write(buffer, 0, temp);
}
}
} catch (IOException e) {
System.out.println(e);
} finally {
try {
fis.close();
fos.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
public static void xcopy(String srcPath, String desPath){
File srcFile = new File(srcPath);
File desFile = new File(desPath);
copyFile(srcFile, desFile);
}
public static void print(String msg){
System.out.println(msg);
}
public static void main(String[] args){
print("hello");
xcopy("/home/test/a","/home/test/t");
}
}