Java ProcessBuilder
One of the core classes for writing operating system processes is the ProcessBuilder. You can contact external scripts or progprogramsside of a Java program using this class to start external prprogramswhich allows you to carry out your desired task.
A group of process attributes is managed by each ProcessBuilder instance. With those properties, a new Process object is created by the start() method. Repeatedly calling the start() function from the same instance will generate new subprocesses with the same or related properties.
- The operating system process creation tool ProcessBuilder can be utilized.
- Before JDK 5.0, only the Runtime.exec() method could be used to create and run processes.
- It extends the Object class.
- This class doesn't have synchronization.
Simple ProcessBuilder Usage
One of the ProcessBuilder's most fundamental uses is when a Java program needs to execute an external script. Say you want to execute myprogram.bat in a Windows environment, for example. We must first create a fresh ProcessBuilder
Constructors
ProcessBuilder(ListString> command) creates a process builder using the operating system program and the arguments that are supplied.
ProcessBuilder(String...) creates a process builder using the operating system program and the arguments that are supplied.
Methods:
1. List command
List command() returns the operating system program and arguments for the process function Object()
Syntax: public List command()
Returns: The program used to build this process, together with any arguments, is returned.
Exceptions: If the parameter is null, a NullPointerException will occur.
Program
import java.io.*;
import java.lang.*;
import java.util.*;
class ProcessBuilderDemo {
public static void main(String[] arg) throws IOException
{
List<String> list = new ArrayList<String>();
list.add("notepad.exe");
ProcessBuilder build = new ProcessBuilder(list);
System.out.println("command: " + build.command());
}
}
The output of the above program
command: [notepad.exe]
2. ProcessBuilder command(List command):
This function sets the operating system program and arguments for the process builder. ProcessBuildercommand(List command)
Syntax: public ProcessBuilder command(List command).
Returns: NO RETURNS
Exception: If the input is null, an exception will occur (NullPointerException).
Program
import java.io.*;
import java.lang.*;
import java.util.*;
class ProcessBuilderDemo {
public static void main(String[] arg) throws IOException
{
List<String> list = new ArrayList<String>();
list.add("notepad.exe");
list.add("xyz.txt");
ProcessBuilder build = new ProcessBuilder(list);
System.out.println("command: " + build.command());
}
The output of the above program
command: [notepad.exe, xyz.txt]
3.ProcessBuilder directory(File directory):
This method establishes the working directory for the process builder. ProcessBuilderdirectory(File directory) The working directory of all subsequent subprocesses launched by an object's start() method will be this one. The parameter may be null, which means that the child process will utilize the working path of the active Java process, typically the directory specified by the system by identifying user.dir.
Syntax: Public ProcessBuilder Directory Syntax (File directory).
Returns: This process builder is returned.
Exceptions: No exceptions.
Program
import java.io.*;
import java.lang.*;
import java.util.*;
class ProcessBuilderDemo {
public static void main(String[] arg) throws IOException
{
List<String> list = new ArrayList<String>();
list.add("notepad.exe");
list.add("abc.txt");
ProcessBuilder build = new ProcessBuilder(list);
build.directory(new File("src"));
System.out.println("directory: " + build.directory());
}
}
The output of the above program
directory: src
4.Map environment():
Map environment(): This process gives a string map representation of the environment of the process builder. The environment is initialized to a duplicate of the active process environment when a process builder is built. The environment for all subsequent subprocesses launched by the object's start() method will be this map.
public Map environment syntax ()
returns the environment of this process builder.
SecurityException: If a security officer is present and access to the specified environment is prohibited by its checkPermission function.
Program
import java.io.*;
import java.util.*;
class ProcessBuilderDemo {
public static void main(String[] arg) throws IOException
{
ProcessBuilder pb = new ProcessBuilder();
Map<String, String>envMap = pb.environment();
for (Map.Entry<String, String>entry :
envMap.entrySet()) {
System.out.println("Key = " + entry.getKey()
+ ", Value = "
+ entry.getValue());
}
}
}
The output of the above program
Key = PATH, Value = /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Key = PROGRAMIZ_COMPILER_SERVICE_HOST, Value = 10.0.10.151
Key = KUBERNETES_PORT, Value = tcp://10.0.0.1:443
Key = PROGRAMIZ_COMPILER_PORT, Value = tcp://10.0.10.151:80
Key = TERM, Value = xterm
Key = PROGRAMIZ_COMPILER_WEB_UI_SEVICE_PORT_80_TCP_PROTO, Value = tcp
Key = KUBERNETES_SERVICE_HOST, Value = 10.0.0.1
Key = PS1, Value =
Key = PROGRAMIZ_COMPILER_WEB_UI_SEVICE_PORT_80_TCP_PORT, Value = 80
Key = PROGRAMIZ_COMPILER_WEB_UI_SEVICE_PORT_80_TCP_ADDR, Value = 10.0.14.233
Key = PROGRAMIZ_COMPILER_PORT_80_TCP, Value = tcp://10.0.10.151:80
Key = PROGRAMIZ_COMPILER_PORT_80_TCP_PROTO, Value = tcp
Key = PWD, Value = /app
Key = KUBERNETES_PORT_443_TCP, Value = tcp://10.0.0.1:443
Key = PROGRAMIZ_COMPILER_PORT_80_TCP_ADDR, Value = 10.0.10.151
Key = PROGRAMIZ_COMPILER_WEB_UI_SEVICE_PORT, Value = tcp://10.0.14.233:80
Key = KUBERNETES_PORT_443_TCP_ADDR, Value = 10.0.0.1
Key = PROGRAMIZ_COMPILER_WEB_UI_SEVICE_SERVICE_HOST, Value = 10.0.14.233Key = PROGRAMIZ_COMPILER_PORT_80_TCP_PORT, Value = 80
Key = KUBERNETES_PORT_443_TCP_PROTO, Value = tcp
Key = KUBERNETES_SERVICE_PORT, Value = 443
Key = PROGRAMIZ_COMPILER_SERVICE_PORT, Value = 80
Key = PROGRAMIZ_COMPILER_WEB_UI_SEVICE_PORT_80_TCP, Value = tcp://10.0.14.233:80
Key = PROGRAMIZ_COMPILER_WEB_UI_SEVICE_SERVICE_PORT, Value = 80
Key = HOSTNAME, Value = programiz-compiler-deployment-544ccf6ccb-zdzgg
Key = KUBERNETES_PORT_443_TCP_PORT, Value = 443
Key = KUBERNETES_SERVICE_PORT_HTTPS, Value = 443
Key = HOME, Value = /home/compiler
5.boolean redirectErrorStream():
RedirectErrorStream() returns a boolean value that indicates whether the program builder blends standard output and standard error. If this attribute is true, then the standard output and any error output from any subsequent subprocesses launched by the object's start() procedure will be combined, allowing both to be read using Process. the method getInputStream(). Correlating error messages and the relevant output is made simpler as a result. False is the initial value.
Public booleanredirectErrorStream is the syntax ().
Returns: The redirectErrorStream property of this process builder.
No exceptions.
Program
import java.io.*;
import java.lang.*;
import java.util.*;
class ProcessBuilderDemo {
public static void main(String[] arg) throws IOException
{
List list = new ArrayList();
list.add("notepad.exe");
list.add("xyz.txt");
ProcessBuilder build = new ProcessBuilder(list);
System.out.println(build.redirectErrorStream());
}
}
6.ProcessBuilder redirectErrorStream(booleanredirectErrorStream):
RedirectErrorStream property of this process builder is set using the method ProcessBuilderredirectErrorStream(booleanredirectErrorStream). The standard output and any error output produced by any later subprocesses launched by this object's start() method will be combined if this property is true, making it possible to read both through using Process.getInputStream() method. As a result, connecting error messages to their associated output is made simpler. False is the initial value.
Public ProcessBuilderredirectErrorStream is the syntax (booleanredirectErrorStream).
This process builder is returned.
No exceptions.
Program
import java.io.*;
import java.lang.*;
import java.util.*;
class ProcessBuilderDemo {
public static void main(String[] arg) throws IOException
{
List list = new ArrayList();
list.add("notepad.exe");
list.add("xyz.txt");
ProcessBuilder build = new ProcessBuilder(list);
build.redirectErrorStream(true);
System.out.println(build.redirectErrorStream());
}
}
The output of the above program
True
7.Process start():
Using the process builder's characteristics, this procedure initiates a new process. The command and parameters specified by the command() will be executed by the new process, which will also have the process environment specified by the environment in its working directory (). Utilizing this technique verifies that the instruction is legitimate for the operating system. The instructions can be used depending on the system, but they must at least contain a list of strings that is neither empty nor null. The first element of this object's command array is passed to the security manager's checkExec method as an input if one is present. A SecurityException can be thrown as a result.
Syntax: start a public process ().
a fresh Process object for controlling the subprocess is returned.
If a command list element is null, an exception called NullPointerException will occur.
Exception: IndexOutOfBounds if the command is an empty list (has size 0).
If a security manager is present and its checkExec method forbids the creation of the subprocess, a security exception will be raised.
In the event of an I/O issue, use IOException.
Program
import java.io.*;
import java.lang.*;
import java.util.*;
class ProcessBuilderDemo {
public static void main(String[] arg) throws IOException
{
List<String> commands = new ArrayList<String>();
commands.add("ls");
commands.add("-l");
commands.add(
"/Users/abhishekverma");
ProcessBuilder pb = new ProcessBuilder(commands);
Process process = pb.start();
BufferedReaderstdInput
= new BufferedReader(new InputStreamReader(
process.getInputStream()));
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
}
}
ProcessBuilderinheritIO():
Fixes the subprocess standard I/O source and destination to match those of the running Java process.
Public ProcessBuilderinheritIO is the syntax ().
This process builder is returned.
No exceptions.
program
import java.io.*;
import java.lang.*;
import java.util.*;
class ProcessBuilderDemo {
public static void main(String[] arg)
throws IOException, InterruptedException
{
ProcessBuilder pb = new ProcessBuilder(
"echo", "hello people\n"
+ "An Example of ProcessBuilder ");
pb.inheritIO();
Process process = pb.start();
process.waitFor();
}
}
The output of the above program
hello people
An Example of ProcessBuilder