Run a .jar file using .sh file in unix

纵然是瞬间 提交于 2020-07-18 05:55:42

问题


I have a jar file DirectoryScanner.jar created in windows 7. I want to execute this jar on a unix server. I ran the following command in putty and the jar run absolutely fine as expected:

java -jar DirectoryScanner.jar

Now I want to create a .sh file on the unix server which on executing can run this jar. I created a file Report.sh in which I wrote following code to execute this jar:

java -cp /home/applvis/Java/UAT/lib/DirectoryScanner.jar com.acc.directory.scanner.SDScanner

But when I execute this command in putty, it shows the following error:

[applvis@bg6lnxebs1 UAT]$ . ./ReportGen.sh
Exception in thread "Main Thread" java.lang.NoClassDefFoundError: com/acc/directory/scanner/SDScanner
Caused by: java.lang.ClassNotFoundException: com.acc.directory.scanner.SDScanner
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: com.acc.directory.scanner.SDScanner.  Program will exit.

Can anyone tell me what exactly I'm doing wrong, or suggest some alternate command.

Both my jar and sh file are in different directories. Even if they are in same directory, I get this error.

Ps. I have many jar files to be executed one after the other. So rather than again and again writing the command to run each jar separartely on unix, I want to create an sh file which will contain the code to run all the jars one after the other. And it will be easier for me to just run the sh file. Hence I need the code to be written in sh file which can run my jars.


回答1:


In your shell script change into the directory containing the jar files. Possibly not the best practice but I use this all the time to emulate a 'working directory' where scripts are started from. This way my shell script can be installed in a scripts directory and my Java can be installed in a lib directory.

Assuming your environment is the same when you execute the script as when you call the java from the command line.

#!/bin/sh

cd /home/applvis/Java/UAT/lib
java -jar DirectoryScanner.jar



回答2:


Depending on the tool you used to generate the JAR, it may have replaced your main class with something else that f.e. sets up the classpath and then calls your class. This happens a lot when generating fat JARs with all the dependencies. Do check the contents of the JAR, as it may contain other JARs in turn.



来源:https://stackoverflow.com/questions/29847709/run-a-jar-file-using-sh-file-in-unix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!