2017-12-19 5 views
0

다른 디렉토리에 주기적으로 복사해야하는 디렉토리를 채울 서비스가 있습니다. 소스는 주기적으로 채워집니다.파일이 일치하지 않으면 하나의 디렉토리를 다른 디렉토리에 반복적으로 복사합니다.

디렉토리를 복사하면 파일이 상당히 커지기 때문에 대상에 파일을 추가하거나 동일한 파일 (예 : 파일 크기 불일치 또는 수정 날짜)이 아닌 파일 만 덮어 쓰려고합니다.

간단한 방법이 있나요? 나는 FileUtils을 알고 있지만 항상 모든 파일을 덮어 쓰는 지, 그리고 여기에서 "병합"이 의미하는 것, 특히 이미 일치하는 파일을 복사하지 않는지 여부는 분명하지 않습니다.

+0

는 지금까지 아무것도 시도? – Verv

+0

파일 크기를 확인하는 대신 이전 파일의 해시와 비교하여 새 파일의 해시를 확인해야합니다. –

+0

'rsync'명령과 비슷합니다. rsync가 수행하는 Java 구현을 위해 네트를 샅샅이 살펴 보셨습니까? 아마 바퀴를 다시 발명하는 것보다 낫지. 그들 중 일부는 빠른 복사를 위해 압축을 지원할 수도 있습니다. – Veera

답변

1

Files.walkFileTree 및 파일의 다른 방법을 수행 할 수 있습니다

public void copyTree(Path source, 
        Path destination) 
throws IOException { 

    Files.walkFileTree(source, 
     new SimpleFileVisitor<Path>() { 
      @Override 
      public FileVisitResult preVisitDirectory(Path dir, 
                BasicFileAttributes attr) 
      throws IOException { 
       Path destPath = destination.resolve(source.relativize(dir)); 
       Files.createDirectories(destPath); 
       return FileVisitResult.CONTINUE; 
      } 

      @Override 
      public FileVisitResult visitFile(Path file, 
              BasicFileAttributes attr) 
      throws IOException { 

       Path destPath = destination.resolve(source.relativize(file)); 

       FileTime sourceTime = Files.getLastModifiedTime(file); 
       FileTime destinationTime = Files.getLastModifiedTime(destPath); 
       if (!Files.exists(destPath) || 
        sourceTime.compareTo(destinationTime) > 0) { 

        Files.copy(file, destPath, 
         StandardCopyOption.COPY_ATTRIBUTES, 
         StandardCopyOption.REPLACE_EXISTING); 
       } 

       return FileVisitResult.CONTINUE; 
      } 
     }); 
} 
관련 문제