使用Ant作为顺手工具

本文介绍如何通过Ant在Java中实现文件下载、解压缩及执行Shell命令等功能,并提供了具体实现的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

source : http://unserializableone.blogspot.com/2009/01/using-ant-as-library.html

Ant has a lot of predefined tasks that could be a great help. You can use them directly from your java code. Here are some examples using Ant to download a file, unzip a package and exec some shell command.

You would need to have
+ ant-1.7.1.jar
+ ant-launcher-1.7.1.jar
+ commons-io-1.3.2.jar (for exec example, found at http://commons.apache.org/io)

in your classpath.

  1. publicclassAntDemo{
  2. /**
  3. *DownloadafileatsourceUrltodest
  4. *
  5. */
  6. publicstaticvoiddownload(URLsourceUrl,Filedest){
  7. ProjectdummyProject=newProject();
  8. dummyProject.init();
  9. GetantGet=newGet();
  10. antGet.setProject(dummyProject);
  11. antGet.setVerbose(true);
  12. antGet.setSrc(sourceUrl);
  13. antGet.setDest(dest);
  14. antGet.execute();
  15. }
  16. /**
  17. *Unzipazipfile
  18. *
  19. */
  20. publicstaticvoidunzip(Filesrc,Filedest){
  21. ProjectdummyProject=newProject();
  22. dummyProject.init();
  23. ExpandantUnzip=newExpand();
  24. antUnzip.setProject(dummyProject);
  25. antUnzip.setSrc(src);
  26. antUnzip.setDest(dest);
  27. antUnzip.execute();
  28. /*antdoesn'tpreservepermissionbits
  29. needtorestorethemmanually*/
  30. Chmodchmod=newChmod();
  31. chmod.setProject(dummyProject);
  32. chmod.setDir(newFile(src.getAbsolutePath().replaceAll(".zip","")));
  33. chmod.setPerm("a+rx");
  34. chmod.setIncludes("**/**");
  35. chmod.execute();
  36. }
  37. /**
  38. *RunashellcommandandreturntheoutputasString
  39. *
  40. */
  41. publicstaticStringexec(Stringcommand,List<STRING>params,FileworkDir){
  42. FileoutputFile;
  43. try{
  44. outputFile=File.createTempFile("exec",".out");
  45. }catch(IOExceptione){
  46. thrownewRuntimeException(e);
  47. }
  48. ProjectdummyProject=newProject();
  49. dummyProject.init();
  50. ExecTaskexecTask=newExecTask();
  51. execTask.setProject(dummyProject);
  52. execTask.setOutput(outputFile);
  53. execTask.setDir(workDir!=null?workDir:newFile(System
  54. .getProperty("user.dir")));
  55. execTask.setExecutable(command);
  56. if(params!=null){
  57. for(Stringparam:params){
  58. execTask.createArg().setValue(param);
  59. }
  60. }
  61. execTask.execute();
  62. FileReaderreader=null;
  63. try{
  64. reader=newFileReader(outputFile);
  65. returnIOUtils.toString(reader);
  66. }catch(Exceptione){
  67. thrownewRuntimeException(e);
  68. }finally{
  69. IOUtils.closeQuietly(reader);
  70. outputFile.delete();
  71. }
  72. }
  73. publicstaticvoidmain(String[]args){
  74. List<STRING>params=Arrays.asList(newString[]{"Hello","World"});
  75. System.out.println(exec("echo",params,null));
  76. }
  77. }

public class AntDemo {

/**
* Download a file at sourceUrl to dest
*
*/
public static void download(URL sourceUrl, File dest) {
Project dummyProject = new Project();
dummyProject.init();

Get antGet = new Get();
antGet.setProject(dummyProject);
antGet.setVerbose(true);
antGet.setSrc(sourceUrl);
antGet.setDest(dest);
antGet.execute();
}

/**
* Unzip a zip file
*
*/
public static void unzip(File src, File dest) {
Project dummyProject = new Project();
dummyProject.init();

Expand antUnzip = new Expand();
antUnzip.setProject(dummyProject);
antUnzip.setSrc(src);
antUnzip.setDest(dest);
antUnzip.execute();

/* ant doesn't preserve permission bits
need to restore them manually */

Chmod chmod = new Chmod();
chmod.setProject(dummyProject);
chmod.setDir(new File(src.getAbsolutePath().replaceAll(".zip", "")));
chmod.setPerm("a+rx");
chmod.setIncludes("**/**");
chmod.execute();
}


/**
* Run a shell command and return the output as String
*
*/
public static String exec(String command, List params, File workDir) {
File outputFile;
try {
outputFile = File.createTempFile("exec", ".out");
} catch (IOException e) {
throw new RuntimeException(e);
}

Project dummyProject = new Project();
dummyProject.init();

ExecTask execTask = new ExecTask();
execTask.setProject(dummyProject);
execTask.setOutput(outputFile);
execTask.setDir(workDir != null ? workDir : new File(System
.getProperty("user.dir")));
execTask.setExecutable(command);
if (params != null) {
for (String param : params) {
execTask.createArg().setValue(param);
}
}

execTask.execute();

FileReader reader = null;
try {
reader = new FileReader(outputFile);
return IOUtils.toString(reader);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(reader);
outputFile.delete();
}
}

public static void main(String[] args) {
List params = Arrays.asList(new String[] { "Hello", "World" });
System.out.println(exec("echo", params, null));
}
}



Just note that you'll need a dummy project for the Ant task. Otherwise you'll get an NullPointerException.

There are a lot of tasks that you could use. The list is here http://ant.apache.org/manual/tasksoverview.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值