简体   繁体   中英

How to extract line with word from string (java_android)

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?

/proc/cpuinfo is just a text file. Just use a BufferedReader and read the contents instead of using ProcessBuilder . Check for the the prefix "Processor" to extract the exact line.

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

I would use a JSONObject. Yo ucan create the object with a "key" processor and the word you want. For example,

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

The line will look like this, {"Processor": "word", "Other Key": "Other Word"}

Then you can write this to a file,

jsonObject.write(Writer writer);

Then you can read the line from the file and use,

jsonObject.getString("Processor");

I used a HashMap incase you have keys and values.

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

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