复制文件时,在扩展文件名之前附加“复制”

时间:2012-03-22 17:52:18

标签: java file copy

假设源文件名为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;
}

2 个答案:

答案 0 :(得分:4)

我将如何做到这一点:

String name = sourceFile.getName();
int i = name.contains(".") ? name.lastIndexOf('.') : name.length();
String dstName = name.substring(0, i) + "(Copy)" + name.substring(i);
File dest = new File(sourceFile.getParent(), dstName);

答案 1 :(得分:0)

Google的Guava库Files.copy(File, File)中有一种便捷方法。