2012-04-20 2 views
2

아래 메소드는 메소드 호출을 통해 수신되는 경로를 "작업 중"디렉토리에서 "이동"디렉토리로 단순히 이동시키는 기능을 가지고 있습니다. 그것은 모두 작동하지만 파일 이름에 .renameTo 메소드가 false를 반환하는 두 개의 확장자 (예 : .xml.md5)가있는 이름의 경우. 아래 코드를 변경하여 실행중인 OS에 관계없이 작동하는 방법이 있습니까? (현재 Windows입니다.)Java 삭제 및 파일 이름 바꾸기

public void moveToDir(String workDir, String moveDir) throws Exception { 
    File tempFile = new File(workDir); 
    File[] filesInWorkingDir = tempFile.listFiles(); 
    for (File file : filesInWorkingDir) { 
     System.out.println(file.getName()); 
     if (new File(moveDir + File.separator + file.getName()).exists()) 
      new File(moveDir + File.separator + file.getName()).delete(); 
     System.out.println(moveDir + File.separator + file.getName()); 
     Boolean renameSuccessful = file.renameTo(new File(moveDir + File.separator + file.getName())); 
     if (!renameSuccessful) throw new Exception("Can't move file to " + moveDir +": " + file.getPath()); 
    } 
} 
+1

이동하려는 파일과 이동하려는 파일에 대한 쓰기 권한이 있는지 확인 했습니까? (file.canWrite()) 아마도이 권한 문제가 될 수 있습니다 ... – Alderath

+1

시도해 FileUtils.moveFile() – Arasu

+0

@ 아라스 -이 시도는 예외 : "원래 파일을 삭제하는 데 실패했습니다 \ xxxxxxxxxxxxxx. xml.md5 '를 복사 한 후'successful \ xxxxxxxxxxxxxx.xml.md5 ' " – Matej

답변

2

나는 코드를 단순화하고 삭제가 성공했는지 확인을 추가했습니다. 시도 해봐.

public void moveToDir(String workDir, String moveDir) { 
    for (File file : new File(workDir).listFiles()) { 
     System.out.println(file.getName()); 
     final File toFile = new File(moveDir, file.getName()); 
     if (toFile.exists() && !toFile.delete()) 
     throw new RuntimeException("Cannot delete " + toFile); 
     System.out.println(toFile); 
     if (!file.renameTo(toFile)) 
     throw new RuntimeException(
      "Can't move file to " + moveDir +": " + file.getPath()); 
    } 
} 
+0

감사합니다. Marko, 지금 작동합니다. 당신이 너무 친절하고 내가 뭘 잘못했는지 그리고 그 방법이 예상대로 작동하지 않는 원인을 알려줄 수 있습니까? – Matej

+0

말하기 어렵습니다. 방금 청소했습니다. 같은 파일을 여러 번 인스턴스화하는 방법 일 수 있습니다. 아마도 그 중 하나가 올바르지 않을 수 있습니다. String concatenanion에 의해 경로를 명시 적으로 결합하고 적절한 생성자를 사용했을 수 있습니다. –