简体   繁体   English

从Java使用groovy.util.AntBuilder

[英]Using groovy.util.AntBuilder from java

In groovy the groovy.util.AntBuilder can be used to eg. 在groovy中,可以使用groovy.util.AntBuilder例如。 unzip a file into a folder: 将文件解压缩到文件夹中:

  AntBuilder ant = new AntBuilder();
  ant.unzip(src: file.getPath(), dest: outputFolder.getPath());

Now I would like to do the same but from java. 现在我想从Java上做同样的事情。 Its not possible to call unzip directly. 无法直接调用解压缩。 I assume thats what the invokeMethod is for: 我假设那是invokeMethod的用途:

  AntBuilder ant = new AntBuilder();
  String[] args = new String[4];
  args[0] = "src";
  args[1] = file.getPath();
  args[2] = "dest";
  args[3] = outputFolder.getPath();
  ant.invokeMethod("unzip", args);

the above gives: 以上给出:

 No signature of method: groovy.util.AntBuilder.unzip() is applicable for argument types: (java.lang.String, java.lang.String, java.lang.String, java.lang.String) values:

Any ideas? 有任何想法吗?

I have tried to google docs/examples for using the AntBuilder from java, but I have only found examples where its used from groovy. 我曾尝试通过google来搜索使用AntBuilder的docs / examples,但仅在groovy中使用过该示例。

Right, got to a computer and gave it a go: 是的,进入一台计算机然后试一下:

Given this Java class: 给定此Java类:

import groovy.util.AntBuilder ;
import java.io.File ;
import java.util.HashMap ;

public class Test {
  public static void main( String[] args ) throws Exception {
    if( args.length != 2 ) {
      System.err.println( "Need 2 args.  Input zip file and output folder" ) ;
      System.exit( 1 ) ;
    }
    final File file = new File( args[ 0 ] ) ;
    final File outputFolder = new File( args[ 1 ] ) ;
    AntBuilder ant = new AntBuilder() ;
    ant.invokeMethod( "unzip", new HashMap() {{
      put( "src", file.getPath() ) ;
      put( "dest", outputFolder.getPath() ) ;
    }} ) ;
  }
}

You can then compile it with: 然后可以使用以下命令进行编译:

javac -cp $GROOVY_HOME/embeddable/groovy-all-2.0.5.jar Test.java 

And then run: 然后运行:

java -cp $GROOVY_HOME/lib/*:. Test /path/to/zip /destination/folder

And it should work 它应该工作

import groovy.lang.Closure;
import groovy.util.AntBuilder;

... ...

final AntBuilder ant = new AntBuilder();
ant.invokeMethod("echo", "copy & sync gestartet...");

ant.invokeMethod("sync", new Object[] { new HashMap<String, String>() {
  {
    this.put("todir", "./myordner2");
    this.put("verbose", "yes");
  }
}, new Closure<Object>(null) {
  @Override
  public Object call(Object... args) {
    ant.invokeMethod("fileset", new Object[] {
        new HashMap<String, String>() {
          {
            this.put("dir", "c:/myordner1/test");
          }
        }});
    return null;
  }
} });

I have found this solution. 我已经找到了解决方案。 ;-) ;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM