2010-03-26 123 views
14

我有两个java.io.File对象,文件1和文件2。我想将文件1中的内容复制到文件2。有没有办法做到这一点没有我不必创建一个读取文件1的方法和写入到file2的Java IO到一个文件复制到另一个

+4

见http://stackoverflow.com/questions/106770/standard-concise-way-to-copy-a-file-in-java – TwentyMiles 2010-03-26 00:19:59

回答

24

不,没有内置的方法来做到这一点。最接近你想要完成的任务是从FileOutputStreamtransferFrom方法,像这样:

FileChannel src = new FileInputStream(file1).getChannel(); 
    FileChannel dest = new FileOutputStream(file2).getChannel(); 
    dest.transferFrom(src, 0, src.size()); 

而且不要忘了处理异常和关闭一切在finally块。

+3

哇。你教过我。 – 2010-03-26 00:56:21

+0

此答案的更完整(正确)版本可在此处获得:http://stackoverflow.com/questions/106770/standard-concise-way-to-copy-a-file-in-java/115086#115086。由于http://stackoverflow.com/users/92937/twentymiles上学我们大家。 – vkraemer 2010-03-26 03:20:19

+0

完整而高效的答案:https://gist.github.com/mrenouf/889747 – 2013-05-08 13:58:38

6

号每次长时间的Java程序员都有自己的效用带,包括这种方法的标准方式。这是我的。

public static void copyFileToFile(final File src, final File dest) throws IOException 
{ 
    copyInputStreamToFile(new FileInputStream(src), dest); 
    dest.setLastModified(src.lastModified()); 
} 

public static void copyInputStreamToFile(final InputStream in, final File dest) 
     throws IOException 
{ 
    copyInputStreamToOutputStream(in, new FileOutputStream(dest)); 
} 


public static void copyInputStreamToOutputStream(final InputStream in, 
     final OutputStream out) throws IOException 
{ 
    try 
    { 
     try 
     { 
      final byte[] buffer = new byte[1024]; 
      int n; 
      while ((n = in.read(buffer)) != -1) 
       out.write(buffer, 0, n); 
     } 
     finally 
     { 
      out.close(); 
     } 
    } 
    finally 
    { 
     in.close(); 
    } 
} 
+0

没有copyFileToInputStream? – 2010-03-26 00:35:21

+0

这是一个*摘录*。 :) – 2010-03-26 00:56:01

21

如果你想偷懒,侥幸从Apache的IOCommons

写最少的代码使用 FileUtils.copyFile(src, dest)
+1

这是要走的路! – 2010-03-26 11:41:04

+1

我是最小代码的粉丝。不知道为什么使用实用程序包是“懒惰”的。我喜欢StringUtils。 – 2014-02-18 20:32:36

6

由于Java 7您可以使用Java标准库中的Files.copy()

您可以创建一个包装方法:

public static void copy(String sourcePath, String destinationPath) throws IOException { 
    Files.copy(Paths.get(sourcePath), new FileOutputStream(destinationPath)); 
} 

,可以通过以下方式使用:

copy("source.txt", "dest.txt"); 
0

的Java 7可以使用Files.copy()而且非常重要的是:待办事项不要忘记创建新文件后关闭的OutputStream。

OutputStream os = new FileOutputStream(targetFile); 
Files.copy(Paths.get(sourceFile), os); 
os.close(); 
相关问题