java - 如何从字符串中提取带有单词的行(java_android)

标签 java android string lookup processor

我有以下代码:

    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/

相关文章:

android - SearchView 文本大小

android - 使用 firebase 发送推送通知 - 致命异常(android)

android - 带有 Assets 数据库的 CursorAdapter

c++ - const char* 有什么异常(exception)吗?

java - 检查字符串中的特定数字 [Java]

python - 在 Python 中解码双重编码的 utf8

java - 如何使用 selenium webdriver 找到这个元素?

java - Base64 编码图像最快的 Java 库是什么?

java - JAXB 与 IDEA + Android 插件上的数据绑定(bind)冲突

java - 为什么 listFiles() 也将目录列为文件?