0

This is for a class. I've never used shell scripting before, but the instructions are to write a script that runs my java program (which is already all set up to take in command line arguments (at least one arg, with an optional second one)). I'm supposed to be able to run it like this:

./script.sh arg1 arg2

But when I do, I get the following error (my java main class name is A1):

  Exception in thread "main" java.lang.NoClassDefFoundError: A1/class
  Caused by: java.lang.ClassNotFoundException: A1.class
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
  Could not find the main class: A1.class.  Program will exit.

This is what my shell script looks like right now:

#!/bin/sh

java -Xmx1024m A1.class $@

Any help is appreciated.

2 Answers 2

3

You need to tell java where to look for your class (using -cp) - either in a directory or a .jar

To find the directory where the script is (as opposed to where it was launched from), you can use: $(dirname $0).

So, for example:

#!/bin/bash

JVM=java
JVM_OPTS="-Xmx1024m"

$JVM $JVM_OPTS -cp $(dirname $0)/myapp.jar A1 "$@"

It's a good idea to be explicit about the shell you want. Also note the quotes around $@, needed for escaped args.

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

1 Comment

Thanks for the help. Turns out all I had to do was get rid of the ".class", but thanks for the tips.
2

Use the classpath flag when running java to tell the virtual machine where your A1.class file is located.

See the doc

Should be something like:

 java -classpath /myfolder A1 $@

Also, do not use the ".class" suffix when running the command.

1 Comment

Thank you very much. All I did was get rid of the ".class" and it works.

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.