DeepSidhu1313
DeepSidhu1313

Reputation: 805

Could not find or load main class when Running java program using Ant?

I am learning Ant to run Java programs with and without building Jar Files.

Here is my simple program i want to run

public class ForDemo {

int i = 0;
byte b = 0;
short s = 0;
double d = 0;
float f = 0;

public ForDemo() {
for (int i = 0; i <= 1000; i++) {
        System.out.println("" + i);
    }
}

public static void main(String[] args) {
    new ForDemo();
}
}

And the build.xml file for Ant

 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
 <project default="run" basedir="." name="">
 <!--this file was created by Eclipse Runnable JAR Export Wizard-->
 <!--ANT 1.7 is required                                        -->

 <target name="compile">
  <javac srcdir="." destdir="." includes="**/*.java" target="1.8">

    <classpath refid="classpath.base" />
  </javac>

  </target>
   <target name="run"  depends="compile">
    <java fork="true" failonerror="yes" classname="ForDemo">
     <arg line=" "/>
     <classpath refid="classpath.base" />
    </java>
   </target>  <!-- Libraries on which your code depends -->

   <path id="classpath.base">                                                                                                                           
      <fileset dir="libs">                                                                                                                          
        <include name="**/*.jar" />                                                                                                          
     </fileset>                                                                                                                                   
     </path>  
    </project> 

But i am getting this error

  run:
  [java] Error: Could not find or load main class ForDemo

  BUILD FAILED

When i run ant in the parent directory of java file command on my Linux Mint 17.1 x64 with oracle jdk 1.8b40.

Upvotes: 3

Views: 3860

Answers (1)

ewan.chalmers
ewan.chalmers

Reputation: 16235

You have not included the output dir (".") of your javac task on the classpath of your java task, so the ForDemo class that you compile there is not on the classpath when java executes.

You could include that dir in your java task like this:

    <classpath>
        <pathelement path="${classpath.base}"/>
        <pathelement location="."/>
    </classpath>

Upvotes: 2

Related Questions