import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Date;
public class aa {
/**
* 复制整个文件夹内容,并替换所有文件中的";"
*
* @param oldPath
* String 原文件路径 如:e:/b/
* @param newPath
* String 复制后路径 如:e:/a/
*/
public void copyFolder(String oldPath, String newPath) {
try {
File filePath = new File(oldPath);
String[] file = filePath.list();
int len =file.length;
for (int i = 0; i < len; i++) {
File temp = this.getLastTimeFile(oldPath, newPath);
System.out.println("**********");
if (temp.isFile()) {
this.writeFile(this.readerFile(temp.toString()), newPath
+ "/" + (temp.getName()).toString());
temp.delete();
}
}
System.out.println("复制文件夹操作 成功执行");
} catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
}
public String readerFile(String filePath) {
String a = "";
File f = new File(filePath);
if (f.exists()) {
try {
// 下为读取文件
BufferedReader raf = new BufferedReader(
new FileReader(filePath));
char[] buf = new char[1024*5];
int len = raf.read(buf);
a = new String(buf, 0, len);
raf.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return a.replaceAll(";", " ");
}
public static void writeFile(String content, String filePath) {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(filePath));
bw.write(content);
bw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
} catch (Exception ex) {
}
bw = null;
}
}
}
public File getLastTimeFile(String oldPath, String newPath) {
File temp0 = null;
File temp1 = null;
try {
// (new File(newPath)).mkdirs();
File filePath = new File(oldPath);
String[] file = filePath.list();
for (int i = 0; i < file.length; i++) {
for (int j = 0; j <file.length; j++) {
if (oldPath.endsWith(File.separator)) {
temp0 = new File(oldPath + file[i]);
temp1 = new File(oldPath + file[j]);
} else {
temp0 = new File(oldPath + File.separator + file[i]);
temp1 = new File(oldPath + File.separator + file[j]);
}
if (temp1.isFile()) {
Date date0 = new Date(temp0.lastModified());
Date date1 = new Date(temp1.lastModified());
if (date0.after(date1)) {
temp0 = temp1;
}
}
}
if (temp0.isDirectory()) {// 如果是子文件夹
copyFolder(oldPath + "/" + file[i], newPath + "/"
+ file[i]);
}
}
System.out.println("得到修改时间最晚的文件");
} catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
return temp0;
}
public static void main(String[] args) {
aa a = new aa();
a.copyFolder("e:/b/", "e:/a/");
}
}