【发布时间】:2012-03-22 17:52:18
【问题描述】:
假设源文件名为Foo.txt。我希望目标文件的名称为Foo(Copy).txt。我希望保留源文件。我该怎么做呢?
/*
* Returns a copy of the specified source file
*
* @param sourceFile the specified source file
* @throws IOException if unable to copy the specified source file
*/
public static final File copyFile(final File sourceFile) throws IOException
{
// Construct the destination file
final File destinationFile = .. // TODO: Create copy file
if(!destinationFile.exists())
{
destinationFile.createNewFile();
}
// Copy the content of the source file into the destination file
FileChannel source = null;
FileChannel destination = null;
try
{
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destinationFile).getChannel();
destination.transferFrom(source, 0, source.size());
}
finally
{
if(source != null)
{
source.close();
}
if(destination != null)
{
destination.close();
}
}
return destinationFile;
}
【问题讨论】:
-
除了像懂事的人一样使用 Commons IO
FileUtils? -
另一种方便的方法是使用 Ant CopyTask:docjar.com/html/api/org/apache/tools/ant/taskdefs/…
-
为什么 skaffman 的评论没有必要或我错过了什么?
-
这不是冷嘲热讽(至少,它不是故意的)。在我看来,手工编写这类东西是愚蠢的,除非有充分的理由不能使用 Commons IO。
-
@mre 我几乎不会把 skaffman 的评论称为讽刺。更能说明问题的是,您已经在这个网站上工作了一年多,拥有 13k+ 的声誉,积极参与 Java 问题,并且在将这个问题发布到网站上之前,没有想过要查看 Apache Commons 以了解毫无疑问的常见任务。在我看来