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
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.

🌐
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.
🌐
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 - Quick guide to how to two ways of running a shell command in Java, both on Windows as well as on UNIX.
🌐
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 - Learn how to run a command using Java in Linux or Windows machine. This execute commands eg. in command prompt in Windows or bash in Linux.
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-execute-native-shell-commands-from-java-program
How to Execute Native Shell Commands from Java Program? - GeeksforGeeks
March 3, 2021 - For example, a Java program running specifically Linux shell commands cannot run as-is on a Windows machine mainly because Windows has a different folder structure and shell commands. ... The first three examples will look at implementing the ProcessBuilder class to run shell commands in Java. The following example is for the RunTime class. Example 1: Loss of portability. This example shows what happens if we execute ...
🌐
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 - In this article, we will discuss how to run terminal commands from Java code. We can execute specific commands from the terminal to execute processes in an operating system. The most used ones are in Linux-based operating systems.
🌐
YouTube
youtube.com › sagar s (vishal)
How to execute linux commands in Java - YouTube
AboutPressCopyrightContact usCreatorsAdvertiseDevelopersTermsPrivacyPolicy & SafetyHow YouTube worksTest new features · © 2024 Google LLC · YouTube, a Google company
Published   July 27, 2016
Views   14K
🌐
Mkyong
mkyong.com › home › java › how to execute shell command from java
How to execute shell command from Java - Mkyong.com
January 3, 2019 - c:mysql then the prompt changes to: mysql> now in this we type sql commands. Can we achieve/automate this with java? ... The article would be even better with a note on how to run a shell file sitting in the resources directory. Thanks for the jump start anyway ! ... I really like your articles on Java. For this one i guess i could not do as mentioned. I googled and figured out that you need to first connect to the linux box from java and then you can execute shell commands.
Find elsewhere
🌐
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 - package crunchify.com.tutorials; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * @author Crunchify.com * Execute Linux commands using Java.
🌐
ExtraVM
thishosting.rocks › how-to-execute-a-shell-command-using-java
How To Execute a Shell Command Using Java
May 19, 2021 - The exec() method is for executing commands directly or running .bat/.sh files. try { // -- Linux -- // Run a shell command // Process process = Runtime.getRuntime().exec("ls /home/mkyong/"); // Run a shell script // Process process = ...
🌐
Princeton CS
introcs.cs.princeton.edu › java › 15inout › linux-cmd.html
Java and the Linux Command Line
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. Bash. If you are using the bash shell, ...
🌐
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.
🌐
GitHub
gist.github.com › 4283217
Executing a linux bash command from a java program and reading the response of it which spans multiple lines · GitHub
Executing a linux bash command from a java program and reading the response of it which spans multiple lines
🌐
Stack Abuse
stackabuse.com › executing-shell-commands-with-java
Executing Shell Commands with Java
May 18, 2020 - In this article, we'll take a look at how we can leverage the Runtime and ProcessBuilder classes to execute shell commands and scripts with Java.
🌐
Blogger
javarevisited.blogspot.com › 2011 › 02 › how-to-execute-native-shell-commands.html
How to Execute Native Shell commands from Java Program? Example
Anyway, if you have no choice and you want to execute native commands from Java then it's good to know that how we can do it, many of you probably know this but for those who don't know and have never done it, we will see through an example. Suppose you want to execute the "ls" command in Linux which lists down all the files and directories in a folder and you want to do it using Java.
Top answer
1 of 3
110

exec does not execute a command in your shell

try

Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});

instead.

EDIT:: I don't have csh on my system so I used bash instead. The following worked for me

Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});
2 of 3
35

Use ProcessBuilder to separate commands and arguments instead of spaces. This should work regardless of shell used:

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(final String[] args) throws IOException, InterruptedException {
        //Build command 
        List<String> commands = new ArrayList<String>();
        commands.add("/bin/cat");
        //Add arguments
        commands.add("/home/narek/pk.txt");
        System.out.println(commands);

        //Run macro on target
        ProcessBuilder pb = new ProcessBuilder(commands);
        pb.directory(new File("/home/narek"));
        pb.redirectErrorStream(true);
        Process process = pb.start();

        //Read output
        StringBuilder out = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null, previous = null;
        while ((line = br.readLine()) != null)
            if (!line.equals(previous)) {
                previous = line;
                out.append(line).append('\n');
                System.out.println(line);
            }

        //Check result
        if (process.waitFor() == 0) {
            System.out.println("Success!");
            System.exit(0);
        }

        //Abnormal termination: Log command parameters and output and throw ExecutionException
        System.err.println(commands);
        System.err.println(out.toString());
        System.exit(1);
    }
}
🌐
Alvin Alexander
alvinalexander.com › java › java-exec-system-command-pipeline-pipe
Java exec: How to execute a system command pipeline in Java | alvinalexander.com
Jumping right in, let's imagine that you want to run the following Unix/Linux command from your Java application: ... package com.devdaily.system; import java.io.IOException; import java.util.*; public class ProcessBuilderExample { public static void main(String[] args) throws IOException, InterruptedException { // you need a shell to execute a command pipeline List<String> commands = new ArrayList<String>(); commands.add("/bin/sh"); commands.add("-c"); commands.add("ls -l /var/tmp | grep foo"); SystemCommandExecutor commandExecutor = new SystemCommandExecutor(commands); int result = commandExecutor.executeCommand(); StringBuilder stdout = commandExecutor.getStandardOutputFromCommand(); StringBuilder stderr = commandExecutor.getStandardErrorFromCommand(); System.out.println("STDOUT"); System.out.println(stdout); System.out.println("STDERR"); System.out.println(stderr); } }
🌐
CodeJava
codejava.net › java-se › file-io › execute-operating-system-commands-using-runtime-exec-methods
How to Execute Operating System Commands in Java
July 27, 2019 - Throughout this tutorial, you will learn how to execute a native command from within a Java program, including sending inputs to and getting outputs from the command.Basically, to execute a system command, pass the command string to the exec() method of the Runtime class.
🌐
Iditect
iditect.com › faq › java › how-to-run-linux-commands-in-java.html
How to run Linux commands in Java?
You can run Linux commands in Java by using the ProcessBuilder class or by executing them through the command-line interface (CLI) using the Runtime.getRuntime().exec() method.