Reputation: 3386
I am able to execute shell commands (that has a return value) in Kotlin [Android] using the following lines of code:
fun getFrequencyLevelsCPU0(): Unit {
val process: java.lang.Process = java.lang.Runtime.getRuntime().exec("su -c cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies")
process.waitFor()
}
The above lines of code are capable of running the shell command but the output of the command should be something as follows if the command was written in the add shell:
500000 851000 984000 1106000 1277000 1426000 1582000 1745000 1826000 2048000 2188000 2252000 2401000 2507000 2630000 2704000 2802000
How can I get these above values returned in the getFrequencyLevelsCPU0() function in Kotlin after executing the shell command?
Upvotes: 0
Views: 3479
Reputation: 1332
There is a kotlin library for easy run external command
Add this gradle dependency:
implementation("com.sealwu:kscript-tools:1.0.2")
And can run comamnd like this:
"cd ~ && ls".runCommand()
Output:
Applications Downloads MavenDep Pictures iOSProjects
Desktop IdeaProjects Movies Public scripts
Documents Library Music StudioProjects
Also you can get the output of command line by using evalBash
val date = "date".evalBash().getOrThrow() //execute shell command `date` and get the command's output and set the content to date variable
println(date) //This will print Fri Aug 19 21:59:56 CEST 2022 on console
val year = date.substringAfterLast(" ") // will get 2022 and assign to year
println(year)
Output:
Fri Aug 19 21:59:56 CEST 2022
2022
More Info: https://github.com/wuseal/Kscript-Tools
Upvotes: 2
Reputation: 1531
Since you have a java.lang.Process
, you can use its getInputStream()
(in Kotlin it can be shortened to just inputStream
) (see JavaDoc here) to read the output, for example:
val output = process.inputStream.bufferedReader().lineSequence().joinToString("\n")
Upvotes: 1