Ashutosh Baheti
Ashutosh Baheti

Reputation: 420

Trying to run Java program with classpath; java is not able to find my original compiled class


java noob here. I am trying to compile a run a java program which uses stanford-corenlp-3.9.1.jar. I am trying to compile this using MacOS terminal. Following are the outputs of various commands

javac QuestionsToAnswer.java
This leads to huge list of errors
QuestionsToAnswer.java:5: error: package edu.stanford.nlp.trees does not exist import edu.stanford.nlp.trees.Tree; ^ QuestionsToAnswer.java:6: error: package edu.stanford.nlp.trees.tregex does not exist import edu.stanford.nlp.trees.tregex.TregexMatcher; ^ ...

So instead I run this:
javac -cp stanford-corenlp-3.9.1.jar QuestionsToAnswer.java
This works as expected and creates a QuestionToAnswer.class file.

Then when I try to run the program
java QuestionsToAnswer
It gives me the following error:
Error: Unable to initialize main class QuestionsToAnswer Caused by: java.lang.NoClassDefFoundError: edu/stanford/nlp/trees/Tree

To fix this I add the classpath to the java command so that it is able to find the Tree Class from stanford's library
java -cp stanford-corenlp-3.9.1.jar QuestionsToAnswer
Then it gives me the following error:
Error: Could not find or load main class QuestionsToAnswer Caused by: java.lang.ClassNotFoundException: QuestionsToAnswer

After adding the classpath, java is not able to find my original class file which is already compiled and present in the directory. What am I doing wrong here?

Upvotes: 0

Views: 65

Answers (1)

JB Nizet
JB Nizet

Reputation: 692231

The jar file must be in the classpath because your code uses classes from this jar. So Java must be able to find them.

The directory containing your class must also be in the classpath otherwise Java can't possibly find it.

java -cp .:stanford-corenlp-3.9.1.jar QuestionsToAnswer

on Unix/MacOS, or

java -cp .;stanford-corenlp-3.9.1.jar QuestionsToAnswer

on Windows.

Upvotes: 1

Related Questions