import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /** * 文件对比复制 * @author JIANGYOUYAO * @date 2021/6/7 0007 */ public class filecopy { static String targetFilePath="/mnt/sdc/webresource"; static String sourceFilePaht="/mnt/sdc/webresourceback"; public static void main(String[] args) throws IOException { File sourceFile=new File(sourceFilePaht); traverseFolder(sourceFile); } public static void traverseFolder(File file) throws IOException { if (file.exists()) { File[] files = file.listFiles(); if (null == files || files.length == 0) { System.out.println("文件夹是空的!"); return; } else { for (File file2 : files) { if (file2.isDirectory()) { //对比target是否存在 final String s = file2.getCanonicalPath().replaceAll("webresourceback", "webresource"); File f=new File(s); if(!f.exists()){ System.out.println("复制文件:" + file2.getAbsolutePath()); f.mkdir(); }else{ System.out.println("文件:" + file2.getAbsolutePath()+"存在"); } traverseFolder(file2); } else { //对比target是否存在,不存在则copy final String s = file2.getCanonicalPath().replaceAll("webresourceback", "webresource"); File f=new File(s); if(!f.exists()){ System.out.println("复制文件:" + file2.getAbsolutePath()); FileInputStream in=new FileInputStream(file2); FileOutputStream out=new FileOutputStream(f); byte[] buff=new byte[1024]; int length=in.read(buff); while (length>0){ out.write(buff,0,length); length=in.read(buff); } out.close(); in.close(); }else{ System.out.println("文件:" + file2.getAbsolutePath()+"存在"); } } } } } else { System.out.println("文件不存在!"); } } }