How to copy files in Groovy

后端 未结 8 1675
余生分开走
余生分开走 2020-12-13 17:37

I need to copy a file in Groovy and saw some ways to achieve it on the web:

1

new AntBuilder().copy( file:\"$sourceFile.canonicalPath\", 
                  


        
8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-13 18:03

    This is the way using platform independent groovy script. If anyone has questions please ask in the comments.

    def file = new File("java/jcifs-1.3.18.jar")
    this.class.classLoader.rootLoader.addURL(file.toURI().toURL())
    
    def auth_server = Class.forName("jcifs.smb.NtlmPasswordAuthentication").newInstance("domain", "username", "password")
    def auth_local = Class.forName("jcifs.smb.NtlmPasswordAuthentication").newInstance(null, "local_username", "local_password")
    
    def source_url = args[0]
    def dest_url = args[1]
    def auth = auth_server
    
    //prepare source file
    if(!source_url.startsWith("\\\\"))
    {
      source_url = "\\\\localhost\\"+ source_url.substring(0, 1) + "\$" + source_url.substring(1, source_url.length());
      auth = auth_local  
    }
    source_url = "smb:"+source_url.replace("\\","/");
    println("Copying from Source -> " + source_url);
    println("Connecting to Source..");
    
    def source = Class.forName("jcifs.smb.SmbFile").newInstance(source_url,auth)
    println(source.canRead());
    
    
    // Reset the authentication to default
    auth = auth_server
    
    //prepare destination file
    if(!dest_url.startsWith("\\\\"))
    {
      dest_url = "\\\\localhost\\"+ dest_url.substring(0, 1) + "\$" +dest_url.substring(2, dest_url.length());
      auth = auth_local  
    }
    
    def dest = null
    dest_url = "smb:"+dest_url.replace("\\","/");
    println("Copying To Destination-> " + dest_url);
    println("Connecting to Destination..");
    
    dest = Class.forName("jcifs.smb.SmbFile").newInstance(dest_url,auth)
    println(dest.canWrite());
    
    if (dest.exists()){
      println("Destination folder already exists");
    }
    source.copyTo(dest);
    

提交回复
热议问题