如何使用java动态地将文件从一个位置复制到另一个位置

问题描述:

我们试图将文件从一个位置复制到另一个位置。我们成功将文件从一个位置移动到另一个位置。但是,我想仅将特定文件动态复制到另一个位置。如何使用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

退房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

我想创建一个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是标准的,但你可以调整它的值!