Adding "Copy" before filename extension when copying files

Let's say the name of the source file Foo.txt

. I want the target file name to be Foo(Copy).txt

. And I want to keep the original file. How can i do this?

/*
 * 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;
}

      

+3


source to share


2 answers


This is how I would do it:



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

      

+4


source


The Google Guava library has a convenient Files.copy method (File, File) .



0


source







All Articles