在学习了java的I/O之后,写了一个复制目录的小练习。
package com.exception.file01;
import java.io.*;
public class CopyDirectory {
public static void main(String[] args) throws IOException {
CopyDire copyDire = new CopyDire();
copyDire.copyDire("E:\\LOL","D:\\LOL"); // 要复制的目录和要复制到那个位置
}
}
class CopyDire {
public void copyDire(String in, String out) throws IOException {
File f1 = new File(in); // "E:\\LOL"
File fn = new File(out); // "D:\\LOL"
if (!fn.exists()) { // 如果要没有这个目录就新建
fn.mkdirs();
}
File[] f2 = f1.listFiles(); // 读取这个目录下的子文件返回File对象组成的数组
// System.out.println(f2.length);
for (File f : f2) { // 将File对象循环
if (f.isDirectory()) { // 如果是目录 使用递归
// System.out.println(f.getAbsolutePath()+"+++"+fn.getAbsoluteFile() + "\\" + f.getName());
copyDire(f.getAbsolutePath(),fn.getAbsoluteFile() + "\\" + f.getName());
}else if(f.isFile()){ // 如果是文件 就复制
FileInputStream fis = null;
FileOutputStream fos = null;
fis = new FileInputStream(f.getAbsoluteFile());
fos = new FileOutputStream(fn.getAbsoluteFile() + "\\" + f.getName());
System.out.println(fn.getAbsoluteFile() + "\\" + f.getName());
byte[] bytes = new byte[1024 * 1024]; // 1mb
int readCount = 0;
while ((readCount = fis.read(bytes)) != -1) {
fos.write(bytes, 0, readCount);
}
// 输出流要刷新
fos.flush();
// 关闭管道
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
}
}
}
}
少年易老学难成,一寸光阴不可轻