6

How to execute a java file by shell script?

1
  • Windows or *nix? Commented Mar 31, 2011 at 10:29

5 Answers 5

6

If it's packed up as a jar:

java -jar jarfile.jar
Sign up to request clarification or add additional context in comments.

Comments

6

If it is a class file:

java myClassFile

If it is a jar file:

java -jar myJarFile.jar

See:

Comments

2

java com.foo.Boo

1 Comment

To compile the .java File --> "javac javafile.java" (generates javafile.class). To run it --> "java javafile"
1

All the answers only show the terminal commands to compile and run .java files but not the shell script to do so.

Below is the shell script. Let's call it compileRunJava.sh

javac $1
java ${1%.java}

You may need to giv terminal the permission to run your script -

$ sudo chmod 754 compileRunJava.sh

Let's say your .java file is Hello.java. To run the script, cd to the directory where you have Hello.java. Run the below command -

$ /path/to/shell/script/directory/compileRunJava.sh Hello.java

Comments

0

There's a nifty little trick after if you're using java 11 or more. To execute a single class you can do the following.

PS: This is for unix based systems, IDK about windows.

Step 1: Create A File by executing the command

$ touch hello

Step 2: Add code to the file by using vi or any other text editor. My code looks like this.

#!/usr/bin/java --source <GET_YOUR_JAVA_VERSION>

public class Main{
    public static void main(String... args){
        System.out.println("Hello");
    }
}

Notice the shebang line. That is required.

Step 3: Make that file executable by executing the following command.

$ chmod +x hello

Step 4: Execute the file

$ ./hello
Hello

This is a great thing that is introduced after java 11. You can read about it more over here.

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.