How to execute an external command (run a process) from Kotlin code?
Hello everyone! I just started learning Kotlin and am writing a small console application. I need to execute an external command, for example, run ping or copy a file using cp. In Java, I used Runtime.getRuntime().exec(), but in Kotlin I see there are some built-in functions like ProcessBuilder, but I don't fully understand how to use them.
I tried writing this code:
```kotlin
fun main() {
val command = "ping -c 4 google.com"
val process = Runtime.getRuntime().exec(command)
val reader = BufferedReader(InputStreamReader(process.inputStream))
var line: String?
while (reader.readLine().also { line = it } != null) {
println(line)
}
}
```
But it only outputs the first line and hangs. Am I doing something wrong? Plus I heard that in Kotl
No answers yet.
Log in to leave an answer