2017-05-26 106 views
-2

我們試圖將文件從一個位置複製到另一個位置。我們成功將文件從一個位置移動到另一個位置。但是,我想僅將特定文件動態複製到另一個位置。如何使用java動態地將文件從一個位置複製到另一個位置

import java.io.File; 

public class fileTranfer { 

    public static void main(String[] args) { 
      File sourceFolder = new File("C:/offcial/BPM/Veriflow"); 
      File destinationFolder = new File("C:/offcial/BPM/Veriflow2"); 

      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())); 
        } 

       } 
       System.out.println(destinationFolder + " files transfered."); 
      } 
      else 
      { 
       System.out.println(sourceFolder + " Folder does not exists"); 
      } 

    } 

} 

如果任何一個有樣品,請給我...

+1

閱讀關於FilenameFilter。但是你的問題很不明確 – Jens

回答

0

退房Apache Commons IO

FileUtils中有相當不錯的實用程序方法來檢查相等性並複製文件和目錄。

如果整個LIB應該矯枉過正,只是來看看進入FileUtils-Class via grepcode :)

+0

下載一個庫文件只是爲了複製一個文件有點過於矯枉過正? – Dolf

+0

可能取決於他們想要做多少文件處理的東西。當他認爲它是過度殺傷時,他可以看看[FileUtils-Class via grepcode](http://grepcode.com/file/repo1.maven.org/maven2/commons-io/commons-io/2.4 /org/apache/commons/io/FileUtils.java/):) – aexellent

1

我想創建一個byte []緩衝區,讀取的第一個文件的內容到緩衝區。然後創建第二個文件File File()爲其指定所需的路徑,並將緩衝的數據放入新文件中。

private static void copyFileUsingStream(File source, File dest) throws IOException { 
    InputStream is = null; 
    OutputStream os = null; 
    try { 
     is = new FileInputStream(source); 
     os = new FileOutputStream(dest); 
     byte[] buffer = new byte[1024]; 
     int length; 
     while ((length = is.read(buffer)) > 0) { 
      os.write(buffer, 0, length); 
     } 
    } finally { 
     is.close(); 
     os.close(); 
    } 
} 

編輯:作業應該進入稱爲緩衝區的字節數組的大小。 1024是標準的,但你可以調整它的值!

相關問題