我能够使用以下代码行在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中编写的,则命令的输出应该如下所示:
500000 851000 984000 1106000 1277000 1426000 1582000 1745000 1826000 2048000 2188000 2252000 2401000 2507000 2630000 2704000 2802000
在执行shell命令之后,如何获得Kotlin中的getFrequencyLevelsCPU0()函数中返回的上述值?
发布于 2022-07-12 23:29:05
由于您有一个java.lang.Process
,所以可以使用它的getInputStream()
(在Kotlin中可以将它缩短为inputStream
) (例如,读取输出的在这里见JavaDoc):
val output = process.inputStream.bufferedReader().lineSequence().joinToString("\n")
发布于 2022-08-20 12:30:32
有一个kotlin库可以方便地运行外部命令。
添加这个等级依赖关系:
implementation("com.sealwu:kscript-tools:1.0.2")
可以像这样运行:
"cd ~ && ls".runCommand()
输出:
Applications Downloads MavenDep Pictures iOSProjects
Desktop IdeaProjects Movies Public scripts
Documents Library Music StudioProjects
此外,还可以使用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)
输出:
Fri Aug 19 21:59:56 CEST 2022
2022
https://stackoverflow.com/questions/72958779
复制相似问题