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
To configure Java, you will need to know which shell you are running. In case you don't know, type the following command: [wayne] ~> echo $SHELL Your shell will likely be bash, tcsh, sh, or ksh. To make sure Linux can find the Java compiler and interpreter, edit your shell login file according to the shell you are using.
🌐
TutorialsPoint
tutorialspoint.com › unix_commands › java.htm
java Command in Linux
The java command in Linux allows us to run a compiled Java application. When we execute this command, it initiates the Java Virtual Machine (JVM) in the background, loads the specified class, and invokes the main() method of that class.
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.

🌐
Linux Hint
linuxhint.com › run-java-command-line-linux
How to Run Java from Command-line in Linux – Linux Hint
To run the java program in Linux, we need to verify if Java Development Kit (JDK) is available in the system and its version. ... The Javac command tool is not available in my system.
🌐
Opensource.com
opensource.com › article › 21 › 10 › check-java-jps
Check Java processes on Linux with the jps command | Opensource.com
October 6, 2021 - On Linux, you can view processes with the ps command. It is the simplest way to view the running processes on your system. $ ps PID TTY TIME CMD 4486 pts/0 00:00:00 bash 66930 pts/0 00:00:00 ps · You can use the ps command to view running Java ...
🌐
Oracle
docs.oracle.com › en › java › javase › 19 › docs › specs › man › java.html
The java Command
December 12, 2022 - Allows user to specify VM options in a file, for example, java -XX:VMOptionsFile=/var/my_vm_options HelloWorld. ... Linux AArch64 only: Specifies the branch protection mode. All options other than none require the VM to have been built with branch protection enabled.
Find elsewhere
🌐
Oracle
java.com › en › download › help › enable_console_linux.html
How do I enable and view the Java Console for Linux or Solaris?
Platform(s): Oracle Enterprise Linux, Oracle Linux, Red Hat Linux, SUSE Linux, Solaris SPARC, Solaris x86, Ubuntu Linux ... The Java Console provides information about the Java version, user home directory, and any error message that occurs while running an applet or application.
🌐
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 - However, the Java program must be compiled using the Java Compiler Command (javac) before being executed through the terminal. Let’s go over the step-by-step procedure. Linux cannot compile or execute Java programs without the Java Development Kit. Therefore, the first step is to ensure the JDK has been installed on your machine.
🌐
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 are providing commands to execute. Notice, for Windows, we are running cmd(command prompt) and for Linux-based operating system sh(shell).
🌐
CodingTechRoom
codingtechroom.com › question › -execute-linux-command-java
How to Execute Linux Commands from Java: A Comprehensive Guide - CodingTechRoom
Solution: Check if the command you are trying to execute exists in your system's PATH. Mistake: Not reading the process output which may lead to a blocking state. Solution: Use Input and Error streams to read the process output and error messages simultaneously. ... Learn how to use CertPathValidator for signature validation and CRL revocation management in Java applications.
🌐
Baeldung
baeldung.com › home › java › core java › how to run a shell command in java
How to Run a Shell Command in Java | Baeldung
January 8, 2024 - So, before we create any Process to run our shell command in, we need to be aware of the operating system on which our JVM is running. Additionally, on Windows, the shell is commonly referred to as cmd.exe. Instead, on Linux and macOS, shell commands are run using /bin/sh.
🌐
Oracle
java.com › en › download › help › linux_x64_install.html
Linux 64-bit installation instructions for Java
The instructions below are for installing version Java 8 Update 73 (8u73). If you are installing another version, make sure you change the version number appropriately when you type the commands at the terminal. Example: For Java 8u79 replace 8u73 with 8u79.
🌐
LinuxVox
linuxvox.com › blog › install-java-linux-command-line
Install Java on Linux via Command Line — linuxvox.com
This blog will guide you through the process of installing Java on Linux using the command line, covering fundamental concepts, usage methods, common practices, and best practices.
🌐
Sertman
sertman.com › 2011 › 12 › linux-commands-in-java.html
Linux Commands in Java
You can use getRuntime method to run linux shell commands from java. Try this example to get memory statistics: int ch; String MemStr ...
🌐
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 - Incidentally, in Linux, an SMB shared file path is in the form "//hostname/sharename/dirname/dirname/filename". Even outside of Java, since backslashes are perilous to Unix-style users. Yes, there is a Java library for working with CIFS file sharing. And no, I don't recommend using Runtime.exec() to execute a series of commands and especially not with redirects.
🌐
UW Computer Sciences
pages.cs.wisc.edu › ~deppeler › cs400 › readings › Linux › command_line.html
Run a Java program from the command line
cd to your program project's folder if it is already written (linux command is: cd ~/private/cs400/workspace/project/ ) If you must edit your program source code, try one of these editors ... vi (or vim - my personal favorite) vi MyProgram.java You will need to learn about modes to use vi - here's a tutorial to help you get started.