62,623
社区成员
发帖
与我相关
我的任务
分享import java.io.*;
import java.util.Vector;
public class Tongbu {
/**
* 同步两个目录,用于备份文件,降低磁盘坏道带来的损失。 同步原则:没有则建立;有则比较文件长度和修改日期,一者不同则更新。
* 文件更新全部是由目录1指向目录2,此代码对目录1不产生任何影响。
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
String strPath = "f:\\文件目录1";
// 源目录,工作目录。
String strPath2 = "e:\\文件目录2";
// 目标目录,备份目录。
// 程序顺利执行的结果是目标目录与源目录完全相同(Thumbs.db文件除外)。
if (!new File(strPath2).exists()) {
// 目标目录不存在时则创建目录。
if(new File(strPath2).mkdir()){
System.out.println("文件夹 "+strPath2+" 创建成功!");
}else{
System.out.println("文件夹 "+strPath2+" 创建失败! 请检查目标路径是否可用!");
System.exit(1);
}
}
Vector<File> vf = new Vector<File>();
getDir(new String(strPath), vf);
for (int i = 0; i < vf.size(); i++) {
String ss = vf.get(i).toString();
String ss1 = (strPath2 + ss.substring(strPath.length()));
File f2 = new File(ss1);
if (!comparef(vf.get(i), f2)) {
copys(vf.get(i), f2);
} else {
// System.out.println("两个文件相同!");
}
}
System.out.println("同步已完成!");
}
static boolean comparef(File f, File f2) {
/**
* 比较两个文件,返回true为相同,返回false为不同。 比较原则:文件长度和最后修改时间都相同,两文件才相同。
*
* @param f
* java.io.File 源文件
* @param f2
* java.io.File 目标文件
*/
if (f.length() != f2.length() || f.lastModified() != f2.lastModified()) {
return false;
} else {
return true;
}
}
static boolean copys(File f, File f2) {
/**
* 文件拷贝或生成空文件夹(单个)
*
* @param f
* java.io.File 源文件(夹)
* @param f2
* java.io.File 目标文件(夹) 此方法有快速copy的效果,缓冲区大小为10K。
*/
try {
if (f.isDirectory()) {
if (f2.mkdirs()) {
System.out.println("文件夹 " + f2 + " 创建成功!");
f2.setLastModified(f.lastModified());
// 修改最后修改时间属性。
return true;
} else {
return false;
}
} else {
if (!f2.toString().endsWith("Thumbs.db")) {
// 去掉缩略图缓存文件,此文件可能导致文件输出流关联目标文件失败!
FileInputStream fis = new FileInputStream(f);
FileOutputStream fos = new FileOutputStream(f2);
byte[] b = new byte[10240];
int s = fis.read(b);
while (s != -1) {
fos.write(b, 0, s);
s = fis.read(b);
}
fis.close();
fos.close();
System.out.println("文件 " + f2 + " 更新成功!");
f2.setLastModified(f.lastModified());// 修改最后修改时间属性。
}
return true;
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件创建失败!可能是磁盘已满或目标文件拒绝访问!");
return false;
} catch (SecurityException e) {
e.printStackTrace();
System.out.println("文件创建失败,可能是因为没有足够的权限!");
return false;
}
}
static void getDir(String strPath, Vector<File> vf) {
/**
* 获得目录中的文件列表
*
* @param strPath
* java.lang.String 源文件
* @param vf
* java.util.Vector 保存文件列表的数组
*/
try {
File f = new File(strPath);
File[] fList = f.listFiles();
for (int j = 0; j < fList.length; j++) {
if (fList[j].isDirectory()) {
vf.add(fList[j]);
getDir(fList[j].getPath(), vf);
} else {
vf.add(fList[j]);
}
}
} catch (Exception e) {
System.out.println("获取源目录列表失败,请检查源目录路径是否正确!");
}
}
}