Setting JAVA_HOME when running Ant from Java

你说的曾经没有我的故事 提交于 2019-11-29 21:16:42

问题


The reason is long and boring, but I need to run an Ant script to compile Java 1.5 code from a Java 1.4 app. I keep getting this error, though:

BUILD FAILED

build.xml:16: Unable to find a javac compiler;
com.sun.tools.javac.Main is not on the classpath.
Perhaps JAVA_HOME does not point to the JDK.
It is currently set to "C:\j2sdk1.4.2_16\jre"

In my code, I have:

Project p = new Project();
p.setUserProperty("ant.file", buildFile.getAbsolutePath());
p.setProperty("java.home", "C:\Program Files\Java\jdk1.6.0_04");
p.fireBuildStarted();
p.init();
// so on and so forth

but it ignores it. I've also tried p.setUserProperty(String, String), but that doesn't do the trick, either. Is there a way to do it without launching a separate process?


回答1:


Does the javac task in your buildfile have fork="yes"? If not, then it doesn't matter what the java.home property is set to; ant will attempt to call the javac Main method in the same java process, which from your error is a JRE, not a JDK.

EDIT Try setting the executable property of your javac task to the full path to the javac binary and add compiler="extJavac" to the task.




回答2:


Shouldn't the backslashes be doubled?

p.setProperty("java.home", "C:\\Program Files\\Java\\jdk1.6.0_04");



回答3:


Have you set environment variables JAVA_HOME and ANT_HOME properly? If you are setting via code it should work though.

Also check if your %JAVA_HOME%\bin directory %ANT_HOME%\bin should be in the environment variable 'path'.

Your problem seems to be with the %JAVA_HOME%\bin not being present in the envt. variable path though.




回答4:


Another way to make this work is to add 'tools.jar' to your classpath. The javac compiler is contained within this jar.

java -cp $JAVA_HOME/lib/tools.jar ...




回答5:


javac option is available in tools.jar. In eclipse, even if your JRE HOME points to a jdk, all the system libraries point to JDK_HOME\jre\lib. There is no tools.jar. You can add tools.jar as an external Jar file. This should solve your issue



来源:https://stackoverflow.com/questions/652053/setting-java-home-when-running-ant-from-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!