Java IO将一个文件复制到另一个 [英] java IO to copy one File to another

查看:178
本文介绍了Java IO将一个文件复制到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

没有内置的方法来做到这一点。最接近你要完成的是来自 FileOutputStream transferFrom 方法,如下所示:

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

不要忘记处理异常,并最终关闭 / code> block。


I have two Java.io.File objects file1 and file2. I want to copy the contents from file1 to file2. Is there an standard way to do this without me having to create a method that reads file1 and write to file2

解决方案

No, there is no built-in method to do that. The closest to what you want to accomplish is the transferFrom method from FileOutputStream, like so:

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

And don't forget to handle exceptions and close everything in a finally block.

这篇关于Java IO将一个文件复制到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆