[英]How to execute shell command in Kotlin and get return value from shell [Android]
我可以使用以下代碼行在 Kotlin [Android] 中執行 shell 命令(具有返回值):
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()
}
上面的代碼行可以運行 shell 命令,但是如果命令寫在 add Z2591C98B70119FE624898B1E424B5E91 中,則命令的 output 應該如下所示:
500000 851000 984000 1106000 1277000 1426000 1582000 1745000 1826000 2048000 2188000 2252000 2401000 2507000 2630000 2704000 2704000 2
執行 shell 命令后,如何在 Kotlin 中的 getFrequencyLevelsCPU0() function 中返回上述這些值?
由於您有一個java.lang.Process
,因此您可以使用它的getInputStream()
(在 Kotlin 中它可以縮短為inputStream
)( 請參閱此處的 JavaDoc )來讀取輸出,例如:
val output = process.inputStream.bufferedReader().lineSequence().joinToString("\n")
有一個 kotlin 庫,便於運行外部命令
添加此 gradle 依賴項:
implementation("com.sealwu:kscript-tools:1.0.1")
並且可以像這樣運行命令:
"cd ~ && ls".runCommand()
Output:
Applications Downloads MavenDep Pictures iOSProjects
Desktop IdeaProjects Movies Public scripts
Documents Library Music StudioProjects
您還可以使用 evalBash 獲取命令行的output
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.