The Internet is an integral part of our lives, so it’s important to use it consciously and without any risks. We know about the importance of online providers that enable safe searching and stable connection. In this article, we will take a close look at the importance of shell command that minimizes the possibility of an error during your work and how to execute it within Java code. There are two possible ways: the first is the Runtime class and that’s the exec method, and the second is the ProcessBuilder instance.
What is a shell and why is it so important?
“In order to present a command-line interface, you should use a computer program named shell. It enables users to control their computer with the help of commands entered with a keyboard. There is no need to control graphical user interfaces (GUIs) with mouse or keyboard combinations,” admits Tom Hayes, a UX designer at Essay Tigers.
Reasons to use a shell:
- You can use a lot of bioinformatics tools with the help of a command-line interface and get more command-line version capabilities. For example, BLAST is accessible to those who know how to deal with a shell.
- You will avoid making the same mistakes caused by manual repetitive work thanks to a shell that makes your work less error-prone.
- Your work will be more reproducible since using a shell your computer keeps a record of your every step. It enables people to re-do the work when needed and address others for checking or applying a process to new data.
Runtime.exec()
Runtime.exec() is a simple high-level class, not customizable at the moment but available in every Java application. It gives the possibility for the application to communicate within its environment. 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 = Runtime.getRuntime().exec("path/to/hello.sh"); // -- Windows -- // Run a command //Process process = Runtime.getRuntime().exec("cmd /c dir C:\\Users\\mkyong"); //Run a bat file Process process = Runtime.getRuntime().exec( "cmd /c hello.bat", null, new File("C:\\Users\\mkyong\\")); StringBuilder output = new StringBuilder(); BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { output.append(line + "\n"); } int exitVal = process.waitFor(); if (exitVal == 0) { System.out.println("Success!"); System.out.println(output); System.exit(0); } else { //abnormal... } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }
Source: mkyong.com
There are exec() method variations at your disposal:
- public Process exec (String command) is used for executing the command within a separate process command.
- public Process exec (String command, String[] envp) that executes the command with an environment variables array that is provided as a Strings array.
- public Process exec (String command, String[] envp, File dir) executes the specified environment variables command from within the dir directory.
- public Process exec (String cmdArray[]) is used for executing an array of Strings commands.
- public Process exec (String cmdArray[], String[] envp) can execute a command with the variables of a specified environment.
- public Process exec (String cmdarray[], String[] envp, File dir) used for the specified environment variables from within the dir directory.
The interpreter can run these processes externally and they aren’t system-dependent. Consider that String command and String cmdArray[] are aimed at the same thing and achieve similar results. You can use whether exec(“dir /folder”, exec(new String[]{“dir”,or “/folder”}.
ProcessBuilder
ProcessBuilder is preferred over the Runtime approach due to its ability to customize some details. It enables the working directory to change a shell command running in using the builder.directory(). And it redirects input and output streams to custom replacements. You can use ProcessBuilders methods to retrieve a list of environment variables in the form of a Map. Moreover, set environment variables for your program.
ProcessBuilder processBuilder = new ProcessBuilder(); // -- Linux -- // Run a shell command processBuilder.command("bash", "-c", "ls /home/mkyong/"); // Run a shell script //processBuilder.command("path/to/hello.sh"); // -- Windows -- // Run a command //processBuilder.command("cmd.exe", "/c", "dir C:\\Users\\mkyong"); // Run a bat file //processBuilder.command("C:\\Users\\mkyong\\hello.bat"); try { Process process = processBuilder.start(); StringBuilder output = new StringBuilder(); BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { output.append(line + "\n"); } int exitVal = process.waitFor(); if (exitVal == 0) { System.out.println("Success!"); System.out.println(output); System.exit(0); } else { //abnormal... } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); }
Source: mkyong.com
Conclusion
This brief tutorial shows that we can execute a shell command in Java using two different ways. Those who want to customize the execution of the spawned process need to use a ProcessBuilder.
This post was last modified on May 19, 2021 5:24 pm