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

Discussions

Running Java Program from Command Line Linux - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Save this question. Show activity on this post. I am not very experience with java and this is driving me crazy. I wrote a java program FileManagement and I need to run it from the command line. More on stackoverflow.com
🌐 stackoverflow.com
Writing Java Code from command in linux, why and how?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnprogramming
7
1
April 1, 2024
Trying (and failing) to run cURL command in JAVA using ProcessBuilder
You aren't doing anything with the output, so while it may be working fine there's no way to tell. You need to store the output in a variable to use it or redirect it to stdout if you just want to have it printed to the console. Also remove the quotes. They are needed for a shell to interpret the input correctly but you are launching the process directly and not going through a shell. This means that the quotes are being part of the url curl is trying to access. More on reddit.com
🌐 r/javahelp
7
5
October 10, 2017
"java: command not found" even though java is installed and in /bin

Check if perhaps 'java' is a script for an interpreter that's not installed, or if it's compiled for the wrong architecture.

More on reddit.com
🌐 r/slackware
17
3
May 17, 2017
🌐
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 - 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 the network interfaces, and more. The ProcessBuilder accepts a command and arguments in an array.
🌐
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 - Now to run the Java program that we have compiled earlier in the second step. We use the java command to run the Java program.
🌐
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 8 different shells available 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 feed them in as part of the exec().
🌐
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.
🌐
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.
Find elsewhere
🌐
Geekboots
geekboots.com › java › run-linux-command
Run Linux Command - Java | Geekboots
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 ·
🌐
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:
🌐
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
🌐
Mkyong
mkyong.com › home › java › how to execute shell command from java
How to execute shell command from Java - Mkyong.com
January 3, 2019 - Hi I am trying to create a Terminal Emulator for Linux using Java… Can you help me by giving a direction.. ... Access denied. Option -c requires administrative privileges. —-how to fix admin issue on windows 8.1 ... The following code allows you to set a timer, restart the timer on keywords, and specify if you want it to be sent to your log or not. This prevents several problems I’ve run into while programming on the command ...
🌐
Quora
quora.com › How-do-I-run-a-Unix-command-from-Java-code
How to run a Unix command from Java code - Quora
Answer (1 of 2): Using the Runtime class of the Java API, you can execute Unix commands from Java code. In order to use the "ls" command, follow this example: [code]import java.io.BufferedReader; import java.io.InputStreamReader; public class RunCommand { public static void main(String[] args...
🌐
Stack Abuse
stackabuse.com › executing-shell-commands-with-java
Executing Shell Commands with Java
May 18, 2020 - In this tutorial, we'll cover how to execute shell commands, bat and sh files in Java. We'll be covering examples for all exec() and ProcessBuilder approaches.
🌐
Coderanch
coderanch.com › t › 426616 › java › run-linux-command-java
run linux command in java (I/O and Streams forum at Coderanch)
I have made a method but it doesn`t work. If i run xterm or an application it works. How can i run linux command and receive the output on java? Cheers! ... The xterm command captures all of ifconfig’s output, and displays it in a window.
🌐
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.
🌐
Reddit
reddit.com › r/learnprogramming › writing java code from command in linux, why and how?
r/learnprogramming on Reddit: Writing Java Code from command in linux, why and how?
April 1, 2024 -

Why exactly would coding from a command line or in linux be preferred to other methods. My professor told us from now on assignments would needed to be coded in the command line and that no windows code would be accepted, this is for the java language. He said it was an important skill for programs and would teach us lower level computer knowledge. I always thought the point of java was that it was portable and it created something called the java virtual machine so that it didn't matter where you coded something. So what exactly would be different if it was coded in linux. Also is there a good place to find out how to do it. I've never really messed with command lines before, the only thing I was able to find was this https://www.youtube.com/watch?v=uA4eQbC3JgA and I wasn't able to get it to work anyway and he isn't using linux anyway.

Top answer
1 of 7
9
Your professor is right: it's a useful skill to be able to compile and run programs from the command line. It comes in handy frequently in the real world. Your professor also has an ulterior motive, though it's not an unreasonable one: they don't want to be in a situation where a student submits code that works fine for them but doesn't work for the professor. IDEs might build your Java code differently than command-line tools do, especially when you have multiple classes spread across multiple files. The professor wants to make sure you don't have any IDE-specific assumptions. The professor also wants to make sure you don't have any Windows-specific assumptions: for example Windows is case-insensitive while Linux is case-sensitive. The professor wants to make sure you use case-sensitive file names. You can still use an IDE. Java is Java. And writing and debugging your code will probably be faster that way. However, once you're done, compile and run your code from the command-line on Linux and make sure it works. If it doesn't, figure out the differences and fix them - for example fix the case of file names. It's worth learning, and it's just a small step to take to ensure your professor will be able to run your code the first try.
2 of 7
2
The command line doesn’t replace an editor, However it can be useful to know what commands are needed to compile & execute a program. It’s also good to have a good understanding of how to SSH into a machine and checks what programs are running. Real servers don’t usually run any type of GUI.
🌐
Sololearn
sololearn.com › en › Discuss › 2190797 › how-to-run-linux-command-by-java
How to run linux command by java | Sololearn: Learn to code for FREE!
Not sure if this applies to Java as well, but try searching "execute scp command with Java". Here's my use case: Admin using a very restrictive desktop app with ssh connection to server needs to run a serverside script. For your use case however, it sounds like you only need to run a small script on the command line, or build out a small app in Java to do what you need.
🌐
CommandLinux
commandlinux.com › home › man page › java
java
March 5, 2026 - Reports information about use of native methods and other Java Native Interface activity. ... Displays version information and exits. See also the -showversion option. ... Specifies that the version specified by the release is required by the class or JAR file specified on the command line.
🌐
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?