2013-05-08 167 views
30

我想將文件從一個位置複製到另一個Java位置。如何將文件從一個位置複製到另一個位置?

這是我到目前爲止有:

import java.io.File; 
import java.io.FilenameFilter; 
import java.util.ArrayList; 
import java.util.List; 
public class TestArrayList { 
    public static void main(String[] args) { 
     File f = new File(
      "D:\\CBSE_Demo\\Demo_original\\fscommand\\contentplayer\\config"); 
     List<String>temp=new ArrayList<String>(); 
     temp.add(0, "N33"); 
     temp.add(1, "N1417"); 
     temp.add(2, "N331"); 
     File[] matchingFiles = null; 
     for(final String temp1: temp){ 
      matchingFiles = f.listFiles(new FilenameFilter() { 
       public boolean accept(File dir, String name) { 
        return name.startsWith(temp1); 
       } 
      }); 
      System.out.println("size>>--"+matchingFiles.length); 

     } 
    } 
} 

這不會複製文件,什麼是做到這一點的最好方法是什麼?

+2

開始[基本I/O](http://docs.oracle.com/javase/tutorial/essential/io/),也嘗試在看看[複製文件或目錄](http://docs.oracle.com/javase/tutorial/essential/io/copy.html) – MadProgrammer 2013-05-08 06:20:38

+0

我的第一個問題是如何存儲該搜索文件? – vijayk 2013-05-08 06:23:18

+0

我不確定爲什麼你需要,但是,看看[Collections](http://docs.oracle.com/javase/tutorial/collections/TOC.html),我會專注於'List ' – MadProgrammer 2013-05-08 06:25:29

回答

59

可以使用this(或任何版本):

Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING); 

另外,我建議使用File.separator/,而不是\\,使其跨多個操作系統,提問/回答符合這個可用here

因爲你不知道如何臨時存儲文件,看看ArrayList

List<File> files = new ArrayList(); 
files.add(foundFile); 

要移動的文件List到一個目錄:

List<File> files = ...; 
String path = "C:/destination/"; 
for(File file : files) { 
    Files.copy(file.toPath(), 
     (new File(path + file.getName())).toPath(), 
     StandardCopyOption.REPLACE_EXISTING); 
} 
+0

Files class自JDK 1.7起可用.http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html – JRR 2013-05-08 06:24:22

+0

僅當您要將整個文件夾從一個位置複製到另一個。但我想先搜索,然後複製只有搜索文件夾。 – vijayk 2013-05-08 06:25:19

+0

@vijayk它也可以用來複制單個文件... – MadProgrammer 2013-05-08 06:26:07

4
public static void copyFile(File oldLocation, File newLocation) throws IOException { 
     if (oldLocation.exists()) { 
      BufferedInputStream reader = new BufferedInputStream(new FileInputStream(oldLocation)); 
      BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(newLocation, false)); 
      try { 
       byte[] buff = new byte[8192]; 
       int numChars; 
       while ((numChars = reader.read( buff, 0, buff.length)) != -1) { 
        writer.write(buff, 0, numChars); 
       } 
      } catch(IOException ex) { 
       throw new IOException("IOException when transferring " + oldLocation.getPath() + " to " + newLocation.getPath()); 
      } finally { 
       try { 
        if (reader != null){      
         writer.close(); 
         reader.close(); 
        } 
       } catch(IOException ex){ 
        Log.e(TAG, "Error closing files when transferring " + oldLocation.getPath() + " to " + newLocation.getPath()); 
       } 
      } 
     } else { 
      throw new IOException("Old location does not exist when transferring " + oldLocation.getPath() + " to " + newLocation.getPath()); 
     } 
    } 
3

在Java> = 7中使用新Java文件類。

創建下面的方法並導入必要的庫。

public static void copyFile(File from, File to) throws IOException { 
    Files.copy(from.toPath(), to.toPath()); 
} 

內主要採用如下的方法創建:

File dirFrom = new File(fileFrom); 
File dirTo = new File(fileTo); 

try { 
     copyFile(dirFrom, dirTo); 
} catch (IOException ex) { 
     Logger.getLogger(TestJava8.class.getName()).log(Level.SEVERE, null, ex); 
} 

注: - fileFrom是要複製到新文件fileTo在不同的文件夾中的文件。

積分 - @Scott:Standard concise way to copy a file in Java?

34

使用流

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

使用通道

private static void copyFileUsingChannel(File source, File dest) throws IOException { 
    FileChannel sourceChannel = null; 
    FileChannel destChannel = null; 
    try { 
     sourceChannel = new FileInputStream(source).getChannel(); 
     destChannel = new FileOutputStream(dest).getChannel(); 
     destChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); 
     }finally{ 
      sourceChannel.close(); 
      destChannel.close(); 
     } 
} 

使用Apache下議院IO LIB:

private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException { 
    FileUtils.copyFile(source, dest); 
} 

使用Java SE 7文件類:

private static void copyFileUsingJava7Files(File source, File dest) throws IOException { 
    Files.copy(source.toPath(), dest.toPath()); 
} 

性能測試:

File source = new File("/Users/pankaj/tmp/source.avi"); 
    File dest = new File("/Users/pankaj/tmp/dest.avi"); 


    //copy file conventional way using Stream 
    long start = System.nanoTime(); 
    copyFileUsingStream(source, dest); 
    System.out.println("Time taken by Stream Copy = "+(System.nanoTime()-start)); 

    //copy files using java.nio FileChannel 
    source = new File("/Users/pankaj/tmp/sourceChannel.avi"); 
    dest = new File("/Users/pankaj/tmp/destChannel.avi"); 
    start = System.nanoTime(); 
    copyFileUsingChannel(source, dest); 
    System.out.println("Time taken by Channel Copy = "+(System.nanoTime()-start)); 

    //copy files using apache commons io 
    source = new File("/Users/pankaj/tmp/sourceApache.avi"); 
    dest = new File("/Users/pankaj/tmp/destApache.avi"); 
    start = System.nanoTime(); 
    copyFileUsingApacheCommonsIO(source, dest); 
    System.out.println("Time taken by Apache Commons IO Copy = "+(System.nanoTime()-start)); 

    //using Java 7 Files class 
    source = new File("/Users/pankaj/tmp/sourceJava7.avi"); 
    dest = new File("/Users/pankaj/tmp/destJava7.avi"); 
    start = System.nanoTime(); 
    copyFileUsingJava7Files(source, dest); 
    System.out.println("Time taken by Java7 Files Copy = "+(System.nanoTime()-start)); 

結果:

/* 
* File copy: 
* Time taken by Stream Copy   = 44582575000 
* Time taken by Channel Copy   = 104138195000 
* Time taken by Apache Commons IO Copy = 108396714000 
* Time taken by Java7 Files Copy  = 89061578000 
*/ 

鏈接:

http://www.journaldev.com/861/4-ways-to-copy-file-in-java

+1

謝謝,Apache Commons FileUtils拯救了我的生命,因爲我需要構建舊的Java 6項目,其中nio軟件包不可用。由於不需要將文件轉換爲Path,因此'FileUtils.copyFile(...)'比nio'Files.copy(...)'更短/方便。 – RAM237 2017-09-01 22:43:59

+1

你也可以嘗試谷歌Guava的lib也...注意一些版本不支持Java 6 ..我會在接下來的幾天更新我的帖子 – 2017-09-03 17:31:01

相關問題