Forum Discussion

indraniria's avatar
indraniria
Contributor
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
    TNeuschwanger
    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);
       log.info 'About to copy ' + sourceStr;
       Files.copy(source, target, opt);
       log.info 'Copy to ' + targetStr + ' complete.';
    };
    
    log.info 'Test Step "' + testRunner.runContext.currentStep.name + '" start...';
    log.info "";
    
    fromStr = "R:\\Temp\\fileToCopy.txt";
    toStr = "R:\\Tmp\\fileToCopyTo.txt";
    copyFile(fromStr, toStr);
    
    log.info "";
    log.info 'Test Step "' + testRunner.runContext.currentStep.name + '" finish...';
    • indraniria's avatar
      indraniria
      Contributor
      CopyOption opt = REPLACE_EXISTING

      What does this mean? What to write in place of “REPLACE_EXISTING”
      • TNeuschwanger's avatar
        TNeuschwanger
        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:
        ATOMIC_MOVE
        Move the file as an atomic file system operation. (did not work in Windows OS)
        COPY_ATTRIBUTES
        Copy attributes to the new file.
        REPLACE_EXISTING
        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);

        to

        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.