0

I have following code:

    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;
 }

and String from /proc/cpuinfo as result. I need to extract processor info (Processor: WordIWantToExtract) as String to put it in the TextView. I did it in Python script (print cpuinfo to the txt file, then lookup line number with word "Processor", return its line number and then printing this line with editing). How can I port this to the Java?

4

3 回答 3

1

/proc/cpuinfo只是一个文本文件。只需使用 aBufferedReader并阅读内容而不是使用ProcessBuilder. 检查前缀“处理器”以提取确切的行。

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));
        ...
    }
}
于 2013-06-18T19:42:11.997 回答
0

I'm not sure to understand well your question but I think you can add this after the while loop:

Matcher matcher = Pattern.compile("Processor: (.*)").matcher(result);
if (matcher.find()) {
    String wordYouWantToExtract = matcher.group(1);
}
于 2013-06-18T19:48:43.050 回答
0

我会使用 JSONObject。您可以使用“关键”处理器和您想要的词创建对象。例如,

Map<String, String> processors = new HashMap<String, String>();
loggingMap.put("Processor", "Word");
JSONObject jsonObject = new JSONObject();
jsonObject.element(processors);

该行将如下所示,{“Processor”:“word”,“Other Key”:“Other Word”}

然后你可以把它写到一个文件中,

jsonObject.write(Writer writer);

然后您可以从文件中读取该行并使用,

jsonObject.getString("Processor");

我使用了 HashMap 以防你有键和值。

于 2013-06-18T19:46:44.497 回答