3

Running into an interesting problem When I run:

$cd /projects/MyProject/
$java -cp . S3Sample

This works fine. However if I run:

$java -cp /projects/MyProject /projects/MyProject/S3Sample
Error: Could not find or load main class .projects.MyProject.S3Sample

Why is that. Did a quick look and can't find the answer. Thanks!

1
  • Is your class inside a package? Commented Jun 17, 2014 at 14:33

3 Answers 3

3

I have this folder structure:

- home
  - org
    - test
      + Foo.java
      + Foo.class

And the code in Foo.java is a simple hello world application:

//Note the usage of the package statement here.
package org.test;

public class Foo {
    public static void main(String[] args) {
          System.out.println("Hello world");
    }
}

Then, in command line, in order to execute Foo.class, I should provide the complete name of the class (I'm in "/home" folder in cmd):

$ java -cp "org/test;." Foo
Exception in thread "main" java.lang.NoClassDefFoundError: Foo (wrong name: org/test/Foo)
$ java -cp "org/test;." org.test.Foo
Hello world

Now, I edit the class above and remove the package sentence:

//no package specified
public class Foo {
    public static void main(String[] args) {
          System.out.println("Hello world");
    }
}

After recompiling the class and executing the same command lines:

$ java -cp "org/test;." Foo
Hello world
$ java -cp "org/test;." org.test.Foo
Exception in thread "main" java.lang.NoClassDefFoundError: org/test/Foo (wrong name: Foo)

TL;DR

Make sure to always specify the full name of the class. Check if your class belongs to a package. Specifying the path of the class to execute is the same as writing the full name of the class, java program will replace / by ..

Sign up to request clarification or add additional context in comments.

Comments

2

You should run

$ java -cp /projects/MyProject S3Sample

The path for class is already CLASSPATH-relative

Comments

1

With java, you specify the fully qualified name of a class containing the main method you want executed. (The launcher will replace / with .). This class needs to be in the classpath. The argument is not a path to a file.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.