2012-08-11 4 views
0
File content[] = new File("C:/FilesToGo/").listFiles(); 

for (int i = 0; i < content.length; i++){      

    String destiny = "C:/Kingdoms/"+content[i].getName();   
    File desc = new File(destiny);  
    try { 
     Files.copy(content[i].toPath(), desc.toPath(), StandardCopyOption.REPLACE_EXISTING); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    }     
} 

이것은 내가 가지고있는 것입니다. 그것은 모든 것을 잘 복사합니다. 하지만 내용 중에 몇 가지 폴더가 있습니다. 폴더가 복사되지만 폴더의 내용은 복사되지 않습니다.디렉토리의 전체 내용을 Java로 다른 내용으로 복사하는 방법은 무엇입니까?

답변

0

재귀. 다음은 rescursion을 사용하여 폴더 시스템을 삭제하는 방법입니다.

public void move(File file, File targetFile) { 
    if(file.isDirectory() && file.listFiles() != null) { 
     for(File file2 : file.listFiles()) { 
      move(file2, new File(targetFile.getPath() + "\\" + file.getName()); 
     } 
    } 
    try { 
     Files.copy(file, targetFile.getPath() + "\\" + file.getName(), StandardCopyOption.REPLACE_EXISTING); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

코드를 테스트하지는 않았지만 작동해야합니다. 기본적으로, 등, 폴더는 모든 아이들을 통해 이동의 경우, 항목을 이동으로 이동하기 위해 그것을 말하는 폴더에 아래로 파고

+0

그러나 이렇게하면 하위 폴더가 삭제되어 내용이 직접 운명에 복사됩니다. 그렇지 않습니까? 하위 폴더도 있어야합니다. – user1541106

+1

이렇게하면 하위 폴더가 삭제되지 않고 Files.copy 메서드가 아무 것도 삭제하지 않습니다. 단순히 새로운 경로에 복사본을 넣습니다. –

+0

Nosuchfileexception C : \ Source \ subfolder \ afile.txt -> C : \ Kingdoms \ Source \ subfolder \ afile.txt 하위 폴더의 내용을 제외한 모든 내용이 복사 됨 – user1541106

2

는 아파치 코 몬즈 IO에 FileUtils을 사용하는 것이 좋습니다겠습니까 :

FileUtils.copyDirectory(new File("C:/FilesToGo/"), 
         new File("C:/Kingdoms/")); 

& 내용을 복사합니다.

0

코드가 작동하려면 Alex Coleman의 대답에서 무엇을 변경해야하는지 명확히하기 만하면됩니다. 다음은 알렉스 코드의 수정 된 버전입니다.

private void copyDirectoryContents(File source, File destination){ 
    try { 
     String destinationPathString = destination.getPath() + "\\" + source.getName(); 
     Path destinationPath = Paths.get(destinationPathString); 
     Files.copy(source.toPath(), destinationPath, StandardCopyOption.REPLACE_EXISTING); 
    }   
    catch (UnsupportedOperationException e) { 
     //UnsupportedOperationException 
    } 
    catch (DirectoryNotEmptyException e) { 
     //DirectoryNotEmptyException 
    } 
    catch (IOException e) { 
     //IOException 
    } 
    catch (SecurityException e) { 
     //SecurityException 
    } 

    if(source.isDirectory() && source.listFiles() != null){ 
     for(File file : source.listFiles()) {    
      copyDirectoryContents(file, new File(destination.getPath() + "\\" + source.getName())); 
     } 
    } 

} 
관련 문제