Java 9 Process API
blog.oio.de
blog.oio.de
try {
Process p = Runtime.getRuntime().exec(
System.getenv("windir") + "\\system32\\tasklist.exe");
BufferedReader input = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = input.readLine()) != null) {
System.out.println(line);
//If line describes a correct process,
//reformat the string to get your information out here.
}
input.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
This should read: println( System.exec( "tasklist.exe" ) );
Yes, there should be a stream interface to the output, yes there should be a more complicated mechanism for working with processes in an object oriented manner, but c'mon guys: most of us just want to execute a command and screw with the string output."Now let's see a slightly more complex example, where one is getting a list of all processes running on the operating system. This is an old implementation with pure Java: [code]"
Meanwhile, further down, the new implementation is:
private static void listProcesses(){
ProcessHandle.allProcesses().forEach((h) -> printHandle(h));
}
private static void printHandle(ProcessHandle procHandle) {
// get info from handle
ProcessHandle.Info procInfo = procHandle.info();
System.out.println("PID: " + procHandle.getPid());
System.out.print("Start Parameters: ");
String[] empty = new String[]{"-"};
for (String arg : procInfo.arguments().orElse(empty)) {
System.out.print(arg + " ");
}
System.out.println();
System.out.println("Path: " + procInfo.command().orElse("-"));
System.out.println("Start: " + procInfo.startInstant().
orElse(Instant.now()).toString());
System.out.println("Runtime: " + procInfo.totalCpuDuration().
orElse(Duration.ofMillis(0)).toMillis() + "ms");
System.out.println("User: " + procInfo.user());
}
I don't disagree that the traditional Java way of chaining InputStreams to BufferedReaders and whatnot makes for verbose code, but there are in fact many libraries like Guava and Apache Commons that'll give you one-liners for these. Much of the Java stdlib's philosophy was inspired by the single responsibility principle, rather than providing sane defaults for chains of common operations.Oh yeah, that would be pipe for Java, possible for a JSR?