Executing command in ProcessBuilder does not seem to work for "java" commands in Windows (Kotlin)

Viewed 472

Currently trying to execute a .jar file programmatically. But to test out java, I tried running the the following:

val p = ProcessBuilder("cmd.exe", "/c", "java", "-version").start()
val results: List<String> = p.inputStream.bufferedReader().readLines()
assertThat("Results should contain java version: ", results, hasItem(containsString("java version")))

However, nothing seems to output.

I am successfully able to run:

val pb = ProcessBuilder("cmd.exe", "/c", "echo", "hello world")

I have tried adding a working directory where the java executable is located, but nothing happens. I am running out of ideas on how to make this work. If I run cmd and type out java -version I get the version information.

What else could I do to get this to work?

1 Answers

ProcessBuilder writes the result of command java -version to error output Process.errorStream, not Process.inputStream.

Try this code:

val results: List<String> = p.errorStream.bufferedReader().readLines()

Also you may try Koproc lib

It's a small Kotlin lib to run process and execute commands based on Java ProcessBuilder

You may run java process with timeout = 120 sec :

val koproc = "java -jar some.jar".startProcess { timeoutSec = 120 }

koproc.use {
    println("Out: ${it.readAvailableOut}")
    println("Err: ${it.readAvailableErrOut}")
}

println("Full result after closing: ${koproc.result}")

Run cmd command:

// 'cmd.exe' process will be closed after timeout
val commandResult = "cmd.exe dirs".startCommand { timeoutSec = 1 }

// But you will get the output
println("Out: ${commandResult.out}")

See examples in unit tests: https://github.com/kochetkov-ma/koproc/blob/main/src/test/kotlin/ru/iopump/koproc/ExtensionKtIT.kt

Related