-1

Hello I have a java program. I have a script that should execute the program. The script looks like this

sh compress.sh -f myfile.txt [-o myfile.hzip -s]

How do i create executable from my java program so that it can execute from this script?

Maverick
  • 91
  • 3
  • 10
  • 1
    Your question is poorly worded. Are you asking how to execute this script from within a JAVA program? – Jared Kipe Mar 17 '13 at 15:34
  • 1
    What i mean to say is that this script should be able to execute my java program. – Maverick Mar 17 '13 at 15:35
  • 2
    If I were you I would create a shell script with the corresponding java command. For example: javac myfile.java java myfile – py_script Mar 17 '13 at 15:35
  • 1
    I think the question is not how to compile the source, but how to start the compiled program. I'd suggest making a jar and then putting something like "java my.jar my.package.main.class $1" ($1 for argument 1) into the shell script. Using eclipse, there is something like file->exportToJar... – ruediste Mar 17 '13 at 15:41

1 Answers1

1

MyApp.java:

public class MyApp {
   public static void main(String []args) {
        //Do something with args...
   }
}

compress.sh:

#!/bin/sh

#Specify your Java class here (must contain a main method)
JAVA_CMD="java MyApp"

#JAR variant (a more common approach)
#JAVA_CMD="java -jar myjar.jar"

#Map script arguments to java app arguments. Use flag specific variables, if it's more convinient for you.
while getopts "f:o:s" opt; do
  case $opt in
    f)
      JAVA_CMD="$JAVA_CMD -f $OPTARG"
      ;;
    o)
      JAVA_CMD="$JAVA_CMD -o $OPTARG"
      ;;
    s)
      JAVA_CMD="$JAVA_CMD -s"
      ;;
    *)
      echo "Invalid usage..." >&2
      exit 1;
      ;;
  esac
done

#Additional validation (required options etc.)
#...

echo "Launching Java: $JAVA_CMD"
$JAVA_CMD

Compile your class, then run the script. You may be required to include an additional classpath argument in JAVA_CMD, if you're using any external libraries.

If you're going to use a JAR, then make sure, that your MANIFEST.mf has all the required information (especially a valid Main-Class entry). Further instructions can be found here.

If this is a Maven project, than you can create an executable JAR in one easy step using Maven Assembly Plugin. Just run mvn assembly:assembly.

Community
  • 1
  • 1
Szymon Jednac
  • 2,969
  • 1
  • 29
  • 43
  • Ok I wrote a file called compress.sh with above script. But how do I pass the command line arguements to my java class ? for example sh compress.sh -f myfile.txt [-o myfile.hzip -s] i should be able to pass myfile.txt name to my java class – Maverick Mar 17 '13 at 20:30
  • 1
    Command line arguments are accessible through the _args_ array in your main method. Executing java MyApp ABCD will result in args[0] == "ABCD". More examples can be found [here](http://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html). – Szymon Jednac Mar 17 '13 at 20:39