目录拷贝——测试代码

package net.wj.test;

import java.io.*;


public class copyDirectory {

public static void main(String args[]) throws IOException {
// 已有文件的路径
String url1 = "D:\\readFile\\";
// 需要备份的那个路径
String url2 = "d:\\bakFile\\";

// 创建文件夹
(new File(url2)).mkdirs();

// 列出所有文件和文件夹
File[] files = (new File(url1)).listFiles();

for (int i = 0; i < files.length; i++) {
// 如果是文件的话
if (files[i].isFile()) {
try {
// 读文件
FileReader aFileReader = new FileReader(files[i]);
// 用来保存文件内容
String detail = "";
// 用缓冲方式读取文件
BufferedReader aBufferedReader = new BufferedReader(aFileReader);
// 读取分行文本
String aTemp = aBufferedReader.readLine();
while (aTemp != null) {
detail += aTemp + "\n";
aTemp = aBufferedReader.readLine();
}
aFileReader.close();
// 写文件
File file = new File(url2 + "/" + files[i].getName());
PrintWriter out = new PrintWriter(new FileWriter(file));
out.print(detail);
out.close();

} catch (FileNotFoundException e) {
System.out.println("文件没有找到");
} catch (IOException e) {
System.out.println("copyFile 出错");
}

//FileInputStream input = new FileInputStream(file[i]);
//FileOutputStream output = new FileOutputStream(url2 + "/"
//+ file[i].getName());
//byte[] b = new byte[1024 * 5];
//int len;
//while ((len = input.read(b)) != -1) {
//output.write(b, 0, len);
//}
//output.flush();
//output.close();
//input.close();
}
// 如果是文件夹的话
if (files[i].isDirectory()) {
copyDirectiory(url2 + "/" + files[i].getName(), url1 + "/"
+ files[i].getName());
}
}
}

public static void copyDirectiory(String file1, String file2)
throws IOException {
// 创建文件夹
(new File(file1)).mkdirs();
// 列出所有文件
File[] files = (new File(file2)).listFiles();
for (int i = 0; i < files.length; i++) {
// 如果是文件的话
if (files[i].isFile()) {
try {
// 读文件
FileReader aFileReader = new FileReader(files[i]);
String detail = "";
BufferedReader aBufferedReader = new BufferedReader(aFileReader);
String aTemp = aBufferedReader.readLine();
while (aTemp != null) {
detail += aTemp + "\n";
aTemp = aBufferedReader.readLine();
}
aFileReader.close();
// 写文件
File file = new File(file1 + "/" + files[i].getName());
PrintWriter out = new PrintWriter(new FileWriter(file));
out.print(detail);
out.close();

} catch (FileNotFoundException e) {
System.out.println("文件没有找到");
} catch (IOException e) {
System.out.println("copyFile 出错");
}

//FileInputStream input = new FileInputStream(file[i]);
//FileOutputStream output = new FileOutputStream(file1 + "/"
//+ file[i].getName());
//byte[] b = new byte[1024 * 5];
//int len;
//while ((len = input.read(b)) != -1) {
//output.write(b, 0, len);
//}
//output.flush();
//output.close();
//input.close();
}
// 如果是文件夹的话
if (files[i].isDirectory()) {
copyDirectiory(file1 + "/" + files[i].getName(), file2 + "/"
+ files[i].getName());
}

}

}
}

你可能感兴趣的:(.net)