2011-01-10 57 views

回答

66
myFile.renameTo(new File("/the/new/place/newName.file")); 

File#renameTo確實是(它不僅可以重命名,而且在目錄間移動,至少是同一個文件系統)。

重命名由此抽象路徑名錶示的文件。

該方法行爲的許多方面本質上取決於平臺:重命名操作可能無法將文件從一個文件系統移動到另一個文件系統,它可能不是原子性的,並且如果文件與目標抽象路徑名已經存在。應始終檢查返回值以確保重命名操作成功。

如果你需要一個更全面的解決方案(如想移動磁盤的文件),看一下Apache的百科全書FileUtils#moveFile

+8

myFile.renameTo(new File(「/ the/new/place/newname.file」)); – djangofan 2011-09-01 23:56:28

+3

是的,不要只給新的父目錄。並確保那裏的路徑已經存在。 – Thilo 2011-09-02 00:14:15

+2

請注意,此命令未更新對象`myFile`的路徑。所以它會指向一個不再存在的文件。 – 2014-12-12 09:15:02

2

您可以執行(在Windows環境中,如copy),該任務的外部工具但是,爲了保持代碼的可移植性,一般的做法是:

  1. 讀取源文件到內存
  2. 寫的內容到一個文件在新的位置
  3. 刪除源文件

File#renameTo只要源位置和目標位置在同一個捲上就會工作。我個人會避免使用它將文件移動到不同的文件夾。

4

要移動一個文件,你也可以使用的Jakarta Commons IO的FileUtils.moveFile

錯誤時,它拋出一個IOException,所以當沒有異常被拋出,你知道該文件被感動了。

35

使用Java 7或更新版本,您可以使用Files.move(from, to, CopyOption... options)

E.g.

Files.move(Paths.get("/foo.txt"), Paths.get("bar.txt"), StandardCopyOption.REPLACE_EXISTING); 

詳情參見

2

Files文檔只需添加源和目標文件夾的路徑。

它會將所有文件和文件夾從源文件夾複製到 目標文件夾。

File destinationFolder = new File(""); 
    File sourceFolder = new File(""); 

    if (!destinationFolder.exists()) 
    { 
     destinationFolder.mkdirs(); 
    } 

    // Check weather source exists and it is folder. 
    if (sourceFolder.exists() && sourceFolder.isDirectory()) 
    { 
     // Get list of the files and iterate over them 
     File[] listOfFiles = sourceFolder.listFiles(); 

     if (listOfFiles != null) 
     { 
      for (File child : listOfFiles) 
      { 
       // Move files to destination folder 
       child.renameTo(new File(destinationFolder + "\\" + child.getName())); 
      } 

      // Add if you want to delete the source folder 
      sourceFolder.delete(); 
     } 
    } 
    else 
    { 
     System.out.println(sourceFolder + " Folder does not exists"); 
    } 
1

試試這個: -

boolean success = file.renameTo(new File(Destdir, file.getName())); 
0
Files.move(source, target, REPLACE_EXISTING); 

可以使用Files對象

瞭解更多關於Files

0

寫到這方法在我自己的項目上做這個事情,只有替換文件,如果現有的邏輯。

// we use the older file i/o operations for this rather than the newer jdk7+ Files.move() operation 
private boolean moveFileToDirectory(File sourceFile, String targetPath) { 
    File tDir = new File(targetPath); 
    if (tDir.exists()) { 
     String newFilePath = targetPath+File.separator+sourceFile.getName(); 
     File movedFile = new File(newFilePath); 
     if (movedFile.exists()) 
      movedFile.delete(); 
     return sourceFile.renameTo(new File(newFilePath)); 
    } else { 
     LOG.warn("unable to move file "+sourceFile.getName()+" to directory "+targetPath+" -> target directory does not exist"); 
     return false; 
    }  
} 
相關問題