Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How to create a process using ProcessBuilder in Java 9?
Java 9 added ProcessHandle interface to Process API to enhance Process class. An instance of the ProcessHandle interface identifies a local process that allows us to query process status and managing processes, and ProcessHandle.Info allows us to use local code because of the need to obtain the PID of a local process.
ProcessBuilder class can be used to create separate operating system processes. In the below example, we can create a process of "notepad" application by using the ProcessBuilder class.
Example
import java.time.ZoneId;
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.io.IOException;
public class ProcessBuilderTest {
public static void main(String args[]) throws IOException {
ProcessBuilder pb = new ProcessBuilder("notepad.exe");
String np = "Not Present";
Process p = pb.start();
ProcessHandle.Info info = p.info();
System.out.printf("Process ID : %s%n", p.pid());
System.out.printf("Command name : %s%n", info.command().orElse(np));
System.out.printf("Command line : %s%n", info.commandLine().orElse(np));
System.out.printf("Start time: %s%n", info.startInstant().map(i -> i.atZone(ZoneId.systemDefault()).toLocalDateTime().toString()).orElse(np));
System.out.printf("Arguments : %s%n", info.arguments().map(a -> Stream.of(a).collect(
Collectors.joining(" "))).orElse(np));
System.out.printf("User : %s%n", info.user().orElse(np));
}
}
The above example launches the notepad application as below
Output
Process ID : 3728 Command name : C:\WINDOWS\System32\notepad.exe Command line : Not Present Start time: 2020-04-20T18:06:30.378 Arguments : Not Present User : Tutorialspoint\User
Advertisements
