简体   繁体   中英

How to execute shell command in Kotlin and get return value from shell [Android]

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?

由于您有一个java.lang.Process ,因此您可以使用它的getInputStream() (在 Kotlin 中它可以缩短为inputStream )( 请参阅此处的 JavaDoc )来读取输出,例如:

val output = process.inputStream.bufferedReader().lineSequence().joinToString("\n")

There is a kotlin library for easy run external command

Add this gradle dependency:

implementation("com.sealwu:kscript-tools:1.0.1")

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 
println(year)

Output:

Fri Aug 19 21:59:56 CEST 2022
2022

More Info: https://github.com/wuseal/Kscript-Tools

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM