Forum Discussion

indraniria's avatar
3 years ago

How do I copy a file from one directory to other using ReadyAPI Groovy Scripting?

I would like to copy a specifice file from one folder location to other using Groovy(Automating testcases using ready API). Kindly help me on the code.  

4 Replies

  • TNeuschwanger's avatar
    Champion Level 2

    Hello indraniria,



    import static java.nio.file.StandardCopyOption.*;
    import java.nio.*
    import java.nio.file.*
    //import java.nio.file.attribute.BasicFileAttributes;
    def copyFile (sourceStr, targetStr) {
       CopyOption opt = REPLACE_EXISTING;
       Path source = Paths.get(sourceStr);
       Path target = Paths.get(targetStr); 'About to copy ' + sourceStr;
       Files.copy(source, target, opt); 'Copy to ' + targetStr + ' complete.';
    }; 'Test Step "' + + '" start...'; "";
    fromStr = "R:\\Temp\\fileToCopy.txt";
    toStr = "R:\\Tmp\\fileToCopyTo.txt";
    copyFile(fromStr, toStr); ""; 'Test Step "' + + '" finish...';
    • indraniria's avatar
      CopyOption opt = REPLACE_EXISTING

      What does this mean? What to write in place of “REPLACE_EXISTING”
      • TNeuschwanger's avatar
        Champion Level 2

        Hello indraniria 


        It means, if the file exists that is getting copied to, it will replace it with what is getting copied from.  Here are some other constants that I got when I googled what that meant.  You could include them all separated by comma (',') if they would help you with what you are trying to do.

        Enum Constants Enum Constant and Description:
        Move the file as an atomic file system operation. (did not work in Windows OS)
        Copy attributes to the new file.
        Replace an existing file if it exists.


        If you comment the line out

        //CopyOption opt = REPLACE_EXISTING

        and change  the following line from

        Files.copy(source, target, opt);


        Files.copy(source, target);

        you will notice when you execute it, it will fail with an error that the file already exists if it does.  You would have to write more code to check for the existence of the file if you don't want to use REPLACE_EXISTING.