You can use java.lang.Runtime.exec to run simple code. This gives you back a Process and you can read its standard output directly without having to temporarily store the output on disk.

For example, here's a complete program that will showcase how to do it:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class testprog {
    public static void main(String args[]) {
        String s;
        Process p;
        try {
            p = Runtime.getRuntime().exec("ls -aF");
            BufferedReader br = new BufferedReader(
                new InputStreamReader(p.getInputStream()));
            while ((s = br.readLine()) != null)
                System.out.println("line: " + s);
            p.waitFor();
            System.out.println ("exit: " + p.exitValue());
            p.destroy();
        } catch (Exception e) {}
    }
}

When compiled and run, it outputs:

line: ./
line: ../
line: .classpath*
line: .project*
line: bin/
line: src/
exit: 0

as expected.

You can also get the error stream for the process standard error, and output stream for the process standard input, confusingly enough. In this context, the input and output are reversed since it's input from the process to this one (i.e., the standard output of the process).

If you want to merge the process standard output and error from Java (as opposed to using 2>&1 in the actual command), you should look into ProcessBuilder.

Answer from paxdiablo on Stack Overflow
🌐
Princeton CS
introcs.cs.princeton.edu › java › 15inout › linux-cmd.html
Java and the Linux Command Line
From the shell, type the java command below. [wayne] ~/introcs/hello> java HelloWorld Hello, World If all goes well, you should see the output of the program - Hello, World.
🌐
TutorialsPoint
tutorialspoint.com › unix_commands › java.htm
java Command in Linux
In this tutorial, we covered the basic syntax of the java command, its various options, how to check for Java installation, and provided a step-by-step guide on creating, compiling, and running a Java program in a Linux environment.
🌐
JavaPointers
javapointers.com › java › java-core › how-to-run-a-command-using-java-in-linux-or-windows
How To Run a Command using Java in Linux or Windows - JavaPointers
May 24, 2020 - In this guide, we will show you how to run a command using Java in Linux or Windows machine. This will execute commands such as in command prompt in Windows or bash in Linux. The Process API in Java lets you execute commands in the System. For example, printing the current directory, showing ...
🌐
LinuxForDevices
linuxfordevices.com › home › how to run a command-line java program on linux?
How to Run a Command-Line Java Program on Linux? - LinuxForDevices
July 19, 2021 - In this tutorial, we will learn about how to run a command-line Java program from the Linux terminal.
Top answer
1 of 10
64

You can use java.lang.Runtime.exec to run simple code. This gives you back a Process and you can read its standard output directly without having to temporarily store the output on disk.

For example, here's a complete program that will showcase how to do it:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class testprog {
    public static void main(String args[]) {
        String s;
        Process p;
        try {
            p = Runtime.getRuntime().exec("ls -aF");
            BufferedReader br = new BufferedReader(
                new InputStreamReader(p.getInputStream()));
            while ((s = br.readLine()) != null)
                System.out.println("line: " + s);
            p.waitFor();
            System.out.println ("exit: " + p.exitValue());
            p.destroy();
        } catch (Exception e) {}
    }
}

When compiled and run, it outputs:

line: ./
line: ../
line: .classpath*
line: .project*
line: bin/
line: src/
exit: 0

as expected.

You can also get the error stream for the process standard error, and output stream for the process standard input, confusingly enough. In this context, the input and output are reversed since it's input from the process to this one (i.e., the standard output of the process).

If you want to merge the process standard output and error from Java (as opposed to using 2>&1 in the actual command), you should look into ProcessBuilder.

2 of 10
27

You can also write a shell script file and invoke that file from the java code. as shown below

{
   Process proc = Runtime.getRuntime().exec("./your_script.sh");                        
   proc.waitFor();
}

Write the linux commands in the script file, once the execution is over you can read the diff file in Java.

The advantage with this approach is you can change the commands with out changing java code.

🌐
Geekboots
geekboots.com › java › run-linux-command
Run Linux Command - Java | Geekboots
Java programming example for run Linux command · By Geekboots · 10/25/2021 · 0 views · Share · trun-linux-command.javaJavaCopy · import java.io.*; public class linux_command { public static void main(String args[]) { String s = null; try { /* Run the Linux command "ls" using the Runtime exec method: */ Process p = Runtime.getRuntime().exec("ls"); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); /* Read the output from the command */ System.out.println("Output of the command:"); while ((s = stdInput.readLine()) != null) System.out.println(s); } catch (IOException e) { System.out.println("Invalid Command!"); } } } /* Output */ Output of the command: armstrong.java arraysum.java weekdayname.java ·
🌐
Linux Hint
linuxhint.com › run-java-command-line-linux
How to Run Java from Command-line in Linux – Linux Hint
Let’s go with the default-jdk command to get it: ... Now, write a Java program in the text file and save it with .java extension. Suppose I created a file named “testing.java” and write a simple program in it: (Keep in mind that your class name should be the same as the file name)
🌐
CommandLinux
commandlinux.com › home › man page › java
java
March 5, 2026 - -version:"1.6.0_13 1.6*&1.6.0_10+" The meaning of the previous example is that the class or JAR file requires either version 1.6.0_13, or a version with 1.6 as a version-id prefix and that is not less than 1.6.0_10. The exact syntax and definition of version strings can be found in Appendix A of the Java Network Launching Protocol & API Specification (JSR-56). For JAR files, the preference is to specify version requirements in the JAR file manifest rather than on the command line.
Find elsewhere
🌐
Medium
beknazarsuranchiyev.medium.com › run-terminal-commands-from-java-da4be2b1dc09
Run terminal commands from Java. In this article, we will discuss how to… | by Beknazar | Medium
April 24, 2022 - We literally do everything from the terminal in Linux to work on the server and sometimes we need to do it from the code. We are going to discuss ProcessBuilder.java and Process.java files. Ok, let’s see one code that can execute commands from the terminal:
🌐
Princeton CS
introcs.cs.princeton.edu › java › linux
Hello World in Java on Linux
August 14, 2019 - To make our textbook libraries accessible to Java, use the command java-introcs instead. For example, type the following two commands to test standard drawing and standard audio: You can use Checkstyle and Findbugs to check the style of your programs and identify common bugs. To run Checkstyle, type the following command in the Terminal: Here is a list of available checks. To run Findbugs, type the following command in the Terminal: Here is a list of bug descriptions. My distribution of Linux is { Gentoo, Debian, Ubuntu, Fedora, Red Hat, SuSE, Mandriva, or Slackware }. How should I modify the instructions?
🌐
Dracula Servers
draculaservers.com › home › how to run java programs in linux terminal?
How to Run Java Programs in Linux Terminal? - Dracula Servers Tutorials
June 30, 2024 - After that, use the following command template: “javac filename.java.” Which, in this case, will become “javac demo.java.” Doing this will create a new file in the same directory as “demo.class”. Once you have the Java Program, you ...
🌐
FOSS Linux
fosslinux.com › home › programming › compile and run java from the linux cli (2026 developer guide)
How to Compile and Run Java from Command-line in Linux
April 29, 2026 - To compile a Java program that references code within that JAR file, you must include it in your compilation command: fosslinux@dev:~$ javac -cp ".:external_libs/utilities.jar" Main.java · The -cp flag defines the classpath. The dot (.) represents the current directory, and the colon (:) separates multiple paths on Linux.
🌐
Coderanch
coderanch.com › t › 751548 › java › Execute-Linux-Command-Return-Output
Execute Linux Command and Return Output (Java in General forum at Coderanch)
May 9, 2022 - For one thing, there's only about ... to Linux users, so you'd have to indicate which one to use. Put the commands into a shell script and exec() something like "/usr/bin/sh /absolute/path/to/my/script". Finally, to capture stdout/stderr or set stdin on Runtime.exec() is a lot messier, if I recall, than in that example. You basically have to pre-allocate Java Streams and ...
🌐
freeCodeCamp
freecodecamp.org › news › how-to-execute-and-run-java-code
How to Execute and Run Java Code from the Terminal
March 10, 2022 - Then we need to execute/run the class file. We need to use the command javac file_name_with_the_extension. For example, as I want to compile my Main.java, I will use the command javac Main.java.
🌐
Mkyong
mkyong.com › home › java › how to execute shell command from java
How to execute shell command from Java - Mkyong.com
January 3, 2019 - I am trying to convert avro to json file through java, But it is not working String output = obj.executeCommand(“java -jar /Users/xyz/Desktop/1server/jboss-as-7.1.1.Final/standalone/deployments/Command.war/WEB-INF/lib/avro-tools-1.7.7.jar tojson /Users/xyz/Desktop/avro/4.avro > /Users/xyz/Desktop/avro/D8EC9CC2A3E049648AFD4309B29D2A0F/4.json”); But this is not working through java file, I ran same command through terminal, avro is converted to json ... Why commands with pattern don’t work? Example: uptime | sed “s/^.* up \+\(.\+\), \+[0-9] user.*$/\1/”
🌐
It's FOSS
itsfoss.com › run-java-program-ubuntu
How to Run Java Programs in Ubuntu
January 11, 2023 - You do not need to specify the class extension here. Just the name of the class. And this time, you use the command java, not javac. ... This will print Hello World on the screen for my program. ... And that’s how you run a Java program in the Linux terminal. This was the simplest of the example.
🌐
Crunchify
crunchify.com › macos tutorials › how to run windows, linux, macos terminal commands in java and return complete result
How to Run Windows, Linux, macOS terminal commands in Java and return complete Result • Crunchify
February 26, 2019 - I hope this tutorial helps you run any linux, macOS terminal commands using simple Java program. Let me know for any questions. If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion. How to create executable .jar file using Linux commands and without Eclipse Shortcut? My Favorite Linux Commands – List of Top 25+ Basic Linux Commands and Cheat Sheet · How to Install Apache Web Server, PHP, Perl on Mac OS X Yosemite
🌐
Stack Overflow
stackoverflow.com › questions › 73274386 › linux-terminal-command-execution-with-java
Linux terminal command execution with java - Stack Overflow
Hi dude, i have one more problem ... i have modify the runCommand order because it wasn't right in that way. I don't know how i can show you, so after this comment i'm going to modify my post for you. So, now the problem is that the CP command does't work, so neither the java -jar works, but the RM yes...