解决Java 调用 Ant 包含 <import> 异常:import requires support in ProjectHelper

本文介绍了一个使用Apache Ant构建工具的示例项目。通过一个具体的Java类`AntTest`,演示了如何初始化Ant项目并运行目标任务。此外,还展示了如何通过XML文件(如a.xml和c.xml)来定义构建过程。

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

package tiger;

import java.io.File;

import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;

public class AntTest {
	private Project project;

	public void init(String _buildFile, String _baseDir) throws Exception {
		project = new Project();

		project.init();

		DefaultLogger consoleLogger = new DefaultLogger();
		consoleLogger.setErrorPrintStream(System.err);
		consoleLogger.setOutputPrintStream(System.out);
		consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
		project.addBuildListener(consoleLogger); 
		
		// Set the base directory. If none is given, "." is used.
		if (_baseDir == null)
			_baseDir = new String(".");

		project.setBasedir(_baseDir);

		if (_buildFile == null)
			_buildFile = new String(
					"E:/JEE/Workspaces/MyEclipse 8.6/Study/src/tiger/a.xml");

		//ProjectHelper.getProjectHelper().parse(project, new File(_buildFile));
		// 关键点
		ProjectHelper.configureProject(project, new File(_buildFile));
	}

	public void runTarget(String _target) throws Exception {
		// Test if the project exists
		if (project == null)
			throw new Exception(
					"No target can be launched because the project has not been initialized. Please call the 'init' method first !");
		// If no target is specified, run the default one.
		if (_target == null)
			_target = project.getDefaultTarget();
		
		// Run the target
		project.executeTarget(_target);

	}

	public static void main(String args[]) {
		try {
			AntTest mytest = new AntTest();
			mytest.init(
					"E:/JEE/Workspaces/MyEclipse 8.6/Study/src/tiger/c.xml",
					".");
			mytest.runTarget(null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 a.xml

<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="runtests" name="TestA">
	<target name="runtests" depends="">
		<echo message="Tiger" />
	</target>
</project>

 c.xml

<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="runtests" name="TestC">
	<import file="a.xml" />
</project>
 
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值