我有以下代码:
private String ReadCPUinfo()
{
ProcessBuilder cmd;
String result="";
try{
String[] args = {"/system/bin/cat", "/proc/cpuinfo"};
cmd = new ProcessBuilder(args);
Process process = cmd.start();
InputStream in = process.getInputStream();
byte[] re = new byte[1024];
while(in.read(re) != -1){
System.out.println(new String(re));
result = result + new String(re);
}
in.close();
} catch(IOException ex){
ex.printStackTrace();
}
return result;
}
和来自/proc/cpuinfo 的字符串作为结果。我需要将处理器信息(处理器:WordIWantToExtract)提取为字符串以将其放入 TextView 中。 我在Python脚本中完成了它(将cpuinfo打印到txt文件,然后使用单词“Processor”查找行号,返回其行号,然后通过编辑打印此行)。我如何将其移植到 Java?
最佳答案
/proc/cpuinfo只是一个文本文件。只需使用 BufferedReader
并读取内容,而不是使用 ProcessBuilder
。检查前缀“Processor”以提取准确的行。
BufferedReader reader =
Files.newBufferedReader(Paths.get("/proc/cpuinfo"), StandardCharsets.UTF_8);
while ((line = reader.readLine()) != null) {
Matcher m = Pattern.compile("Processor: (.*)").matcher(line);
if (m.find()) {
System.out.println("Processor is " + m.group(1));
...
}
}
关于java - 如何从字符串中提取带有单词的行(java_android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17177421/