Thursday, April 14, 2011

Setting JAVA_HOME when running Ant from Java

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?

From stackoverflow
  • Shouldn't the backslashes be doubled?

    p.setProperty("java.home", "C:\\Program Files\\Java\\jdk1.6.0_04");
    
    Adam Crume : They were. I think something went wrong when pasting to StackOverflow.
  • 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.

    Adam Crume : Adding fork="yes" does help -- at least javac runs, but it's still the wrong version.
    Adam Crume : I was looking for something like the "executable" property and just didn't see it. It's annoying that I have to set it for each javac task, but it works. Thanks.
  • 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.

0 comments:

Post a Comment