2014-02-25 46 views
0

如何將文件和目錄移動到Java中的另一個目錄中?我使用這種技術來複制,但我需要移動如何移動文件和目錄

File srcFile = new File(file.getCanonicalPath()); 
    String destinationpt = "/home/dev702/Desktop/svn-tempfiles"; 

    copyFiles(srcFile, new File(destinationpt+File.separator+srcFile.getName())); 
+3

可能重複[移動/複製文件中的Java操作](http://stackoverflow.com/questions/300559/move -copy-file-operations-in-java) –

+1

@EelLee其中的一些答案相當過時。 – assylias

回答

1

java.io.File中不包含任何準備化妝移動文件的方法,但你可以用以下兩種方式解決方法:

  1. File.renameTo()

  2. 複製到新的文件,並刪除原文件。

    public class MoveFileExample 
    { 
        public static void main(String[] args) 
        { 
        try{ 
    
        File afile =new File("C:\\folderA\\Afile.txt"); 
    
        if(afile.renameTo(new File("C:\\folderB\\" + afile.getName()))){ 
        System.out.println("File is moved successful!"); 
        }else{ 
        System.out.println("File is failed to move!"); 
        } 
    
    }catch(Exception e){ 
        e.printStackTrace(); 
    } 
    } 
    } 
    

用於複製和刪除

public class MoveFileExample 
{ 
    public static void main(String[] args) 
    { 

     InputStream inStream = null; 
    OutputStream outStream = null; 

     try{ 

      File afile =new File("C:\\folderA\\Afile.txt"); 
      File bfile =new File("C:\\folderB\\Afile.txt"); 

      inStream = new FileInputStream(afile); 
      outStream = new FileOutputStream(bfile); 

      byte[] buffer = new byte[1024]; 

      int length; 
      //copy the file content in bytes 
      while ((length = inStream.read(buffer)) > 0){ 

       outStream.write(buffer, 0, length); 

      } 

      inStream.close(); 
      outStream.close(); 

      //delete the original file 
      afile.delete(); 

      System.out.println("File is copied successful!"); 

     }catch(IOException e){ 
      e.printStackTrace(); 
     } 
    } 
} 

希望它能幫助:)

3

你可以試試這個:

srcFile.renameTo(new File("C:\\folderB\\" + srcFile.getName())); 
+0

謝謝..我的問題解決了 –

+0

同樣我需要將目錄和文件同時移動到另一個目錄 –

+2

這也可以將文件移動到另一個目錄 – Sathesh