user3235881
user3235881

Reputation: 487

Compile and execute java via bash shell

I'm trying to write a shell code that will execute my Java program. I tried this:

#!/bin/sh
COMPILECMD="javac server.jar"
RUNCMD="java -jar server.jar 12777"

$COMPILECMD
$RUNCMD

But I got this error:

error: Class names, 'server.jar', are only accepted if annotation processing is explicitly requested 1 error Failed to load Main-Class manifest attribute from server.jar

In the command line I don't use the jar file, I just compile and then execute:

javac server.java 
java server 12777

Upvotes: 2

Views: 7335

Answers (2)

BRPocock
BRPocock

Reputation: 13914

The typical way to build a Java program into a JAR file from the shell is to use the ant utility.

Its home (and documentation) is here: http://ant.apache.org/

Essentially, you'd write (or use a tool to write) a build.xml in your project folder, and then run ant to compile, bundle, et al.

(Disclaimer: I'm not a fan of Ant, but it is, I believe, the most common/popular tool in the Java universe for this task.)


You can also use traditional Unix Makefiles, if you're familiar with them. Some rules like:

     CLASSES= Server.class Supporting.class

     %.class:   %.java
           javac $<

     %.jar:  $(CLASSES) Manifest.mf
           jar cfm $@ Manifest.mf $(CLASSES)

You could also use a straight-ahead shell script:

      javac Server.java
      javac Supporting.java
      jar cfm Server.jar Manifest.mf Server.class Supporting.class

However, maintaining this is liable to be a nightmare if your project grows beyond a few files.


There are other tools available, as well, but these are the most typical ones I know of.

Upvotes: 2

tom87416
tom87416

Reputation: 542

I think you get wrong understanding. jar is created by jar command not by javac command.

jar command create a jar file (zip file containing all the class inside) javac command just compile and transform .java to .class only

Example compile-command:

javac server.java; jar cvf server.jar server.class

You may find the following link helping. http://docs.oracle.com/javase/tutorial/deployment/jar/build.html

Upvotes: 1

Related Questions