Java NoClassDefFoundError with Ant

I have a third party .jar

file in a folder res/lib

. ANT build.xml

looks like this:

<?xml version="1.0"?>
<project name="my.project" basedir="." default="build">
    <property name="src.dir" value="src"/>
    <property name="build.dir" value="build/classes"/>

    <path id="master-classpath">
        <fileset dir="res/lib">
            <include name="*.jar"/>
        <pathelement path="${build.dir}"/>

    <target name="build">
        <mkdir dir="${build.dir}"/>
        <javac destdir="${build.dir}" optimize="true">
            <src path="${src.dir}"/>
            <classpath refid="master-classpath"/>


The file is .java

as follows:

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;

public class IO {
    public static void readCSVFile(File file) throws IOException {
        FileReader in = new FileReader(file);
        Iterable<CSVRecord> record = CSVFormat.DEFAULT.parse(in);


Compiling is OK, but I got a runtime error: java.lang.NoClassDefFoundError: org/apache/commons/csv/CSVFormat

. I think there is something wrong with the classpath, but it seems fine to me.


It works if I use java -cp path;. Main

. I tried to write an ANT script to run it:

<target name="run">
    <java classname="Main">
        <classpath refid="master-classpath"/>


I write ant run

on the command line, I receive BUILD SUCCESSFUL

and nothing happens.


source to share

3 answers

Your assembly file compiles your code and includes a third party Jar in the classpath so that the compiler can find the classes your code depends on (for example org.apache.commons.csv.CSVRecord


Likewise, when running your main class with java

your JVM, it needs to know where the third party classes exist. Otherwise, the class loader will not be able to load these classes. So in your example, you should still call the main class like this:

java -cp pathtoyourlib;. Main


In other words, they are two different concepts of "classpath": one classpath is used by the compiler to know where to look for each reference class in each class to be compiled, while the other is used by the JVM to know where to load the classes when they are dynamically called.



There is no (visible) main method in your class

public static void main(String[] args){
    IO.readCSVFile(File file)


You need to pass the classpath when running the file

java -cp yourclasspath




You are stating that compilation is fine, but you are not showing how you run the java program ..... So to be clear, ANT exits without error? Is this a problem with starting compilation of java program from command line?

If I'm right, two problems arise:

  • There is no main class in your java program (required after running from command line)
  • The bucks of your program depend on my being included in the classpath when running the java program.


All Articles