2012-09-27 5 views
0

renameTo()를 사용하여 한 디렉토리에서 다른 디렉토리로 파일을 이동하려고합니다. 그러나 renameTo는 작동하지 않습니다 (파일의 이름을 바꾸거나 이동하지 않음). 기본적으로 동일한 파일 이름을 가진 파일을 먼저 삭제 한 다음 anoter 디렉토리의 파일을 원래 파일을 삭제 한 동일한 위치로 복사 한 다음 동일한 이름으로 새 파일을 복사합니다.파일을 삭제하고 java 디렉토리의 파일로 이동

//filePath = location of original file with file name appended. ex: C:\Dir\file.txt 
    //tempPath = Location of file that I want to replace it to file file without the file name. ex: C:\AnotherDir 

    int pos = filePath.indexOf("C:\\Dir\\file.txt"); 
    //Parse out only the path, so just C:\\Dir 
    String newFilePath = filePath.substring(0,pos-1); 

    //I want to delete the original file 
    File deletefile = new File(newFilePath,"file.txt"); 

    if (deletefile.exists()) { 
     success = deletefile.delete(); 
    } 


    //There is file already exists in the directory, but I am just appending .tmp at the end 
    File newFile = new File(tempPath + "file.txt" + ".tmp"); 

    //Create original file again with same name. 
    File oldFile = new File(newFilePath, "file.txt"); 

    success = oldFile.renameTo(newFile); // This doesnt work. 

내가 잘못하고있는 것을 말해 줄 수 있습니까?

도움 주셔서 감사합니다.

+0

무엇이 작동하지 않습니까? 어떤 종류의 오류 메시지가 나옵니까? 프로그램이 정상적으로 종료합니까? –

답변

5

"C:\\Dir\\file.txt" 문자열 리터럴에서 백 슬래시를 이스케이프 처리해야합니다. 또는 File.separator을 사용하여 경로를 구성하십시오. 게시 된 코드 (...ex: C:\AnotherDir)의 commments로

File newFile = new File(tempPath + File.separator + "file.txt" + ".tmp"); 
           //^^^^^^^^^^^^^^^^ 

tempPath 더 후행 슬래시 문자가 없음을 나타냅니다

또한, newFile의 경로가 제대로 구성되어 있는지 확인합니다.

+0

아, 자바가 원시 문자열 지원을 얻으려고 할 때, 심지어 C++도 그것을 가지고 있습니다. – Benj

+0

Acutally, 나는 그것을하고있다. 내 게시물을 업데이트했습니다. 감사. – Tony

+0

@ 토니, 업데이트 된 답변. – hmjd

0

파일을 대상 디렉터리로 이동 한 후 이동 한 파일을 원본 폴더에서 3 가지 방법으로 삭제하고 마침내 프로젝트에서 3 번째 접근 방식을 사용하고 있습니다.

첫번째 방법 :

File folder = new File("SourceDirectory_Path"); 
    File[] listOfFiles = folder.listFiles(); 
    for (int i = 0; i < listOfFiles.length; i++) { 
    Files.move(Paths.get("SourceDirectory_Path"+listOfFiles[i].getName()), Paths.get("DestinationDerectory_Path"+listOfFiles[i].getName())); 
    } 
    System.out.println("SUCCESS"); 

두번째 방법 :

Path sourceDir = Paths.get("SourceDirectory_Path"); 
    Path destinationDir = Paths.get("DestinationDerectory_Path"); 
     try(DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourceDir)){ 
     for (Path path : directoryStream) { 
      File d1 = sourceDir.resolve(path.getFileName()).toFile(); 
      File d2 = destinationDir.resolve(path.getFileName()).toFile(); 
      File oldFile = path.toFile(); 
      if(oldFile.renameTo(d2)){ 
       System.out.println("Moved"); 
      }else{ 
       System.out.println("Not Moved"); 
      } 
     } 
    }catch (Exception e) { 
     e.printStackTrace(); 
    } 

세번째 방법 :

Path sourceDirectory= Paths.get(SOURCE_FILE_PATH); 
      Path destinationDirectory = Paths.get(SOURCE_FILE_MOVE_PATH); 
      try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourceDirectory)) { 
       for (Path path : directoryStream) {          
        Path dpath = destinationDirectory .resolve(path.getFileName());          
        Files.move(path, dpath, StandardCopyOption.REPLACE_EXISTING); 
       } 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
코딩

해피! :)

관련 문제