/** * 文件目录检查拷贝与更新 * By 小屋 * Time 2010-8-30 */ package xw; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; public class FindDirectoriesAndFiles { public static int i = 0; public static void main(String[] args) { FindDirectoriesAndFiles use = new FindDirectoriesAndFiles(); use .findDirectories( "C://Documents and Settings//Administrator//桌面//ext", "H://ext"); if (i == 0) { System.out.println("没用可更新的文件"); } else { System.out.println("已更新" + i + "个文件目录"); } } public boolean findDirectories(String srcPath, String targetPath) { findFiles(srcPath, targetPath); File direcoties[] = new File(srcPath).listFiles(); if (direcoties != null) { for (File file : direcoties) { String tempsrcPath = ""; String temptargetPath = ""; if (file.isDirectory()) { // 源目录下一级子目录 tempsrcPath = srcPath + "/" + file.getName(); // 判断目标目录是否存在此子目录 temptargetPath = targetPath + "/" + file.getName(); File ChildTargetDirecotry = new File(temptargetPath); // 如果不存在 if (!ChildTargetDirecotry.exists()) { System.out.println("找到一个不存在的目录:" + ChildTargetDirecotry.getAbsolutePath()); ChildTargetDirecotry.mkdir(); System.out.println(ChildTargetDirecotry .getAbsolutePath() + "创建成功/n"); i++; } findDirectories(tempsrcPath, temptargetPath); } } } return false; } public void findFiles(String directoryPath, String targetPath) { File[] files = new File(directoryPath).listFiles(); if (files != null) { for (File file : files) { if (file.isFile()) { // 判断目录目录是否有此文件 String tempTargetFile = targetPath + "/" + file.getName(); File tempFile = new File(tempTargetFile); // 如果存在,判断其修改时间 if (tempFile.exists()) { if (file.lastModified() > tempFile.lastModified()) { System.out.println(tempFile.getAbsolutePath() + "已有新版本"); copy(file, tempFile); } } else { // 如果不存在 ,创建新文件 System.out.println("找到一个新文件:" + file.getAbsolutePath()); copy(file, tempFile); } } } } } public void copy(File file, File tempFile) { try { FileInputStream input = new FileInputStream(file); FileOutputStream output = new FileOutputStream(tempFile); int c; byte buffer[] = new byte[1024 * 1024 * 50]; while ((c = input.read(buffer)) != -1) { for (int i = 0; i < c; i++) output.write(buffer[i]); } input.close(); output.flush(); output.close(); tempFile.setLastModified(file.lastModified()); System.out.println("成功更新文件:" + tempFile.getAbsolutePath() + "/n"); i++; } catch (Exception e) { e.printStackTrace(); } } } 简单的文件目录对比.!