Search code examples
javaandroidprocessbuilder

Pipe ("|") and grep doesn't work at ProcessBuilder in Android


I want to get total RAM on Android:

       private String getTotalRAM() 
       {
         ProcessBuilder cmd;
         String result="";

         try{
          String[] args = {"/system/bin/sh", "-c", "cat -n /proc/meminfo | grep MemTotal"};
          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;
        } 

If there are not grep MemTotal, cat returns me a whole info about memory. When I want to get just one line with grep, I get nothing. How can i fix this? I just want to get total available RAM at this moment.


Solution

  • As @Joachim suggests you are likely to find this works for you.

    BufferedReader pmi = new BufferedReader(new FileReader("/proc/meminfo"));
    try {
      String line;
      while ((line = pmi.readLine()) != null)
        if (line.contains("MemTotal"))
           // get the second word as a long.
           return Long.parseLong(line.split(" +",3)[1]); 
      return -1;
    } finally {
      pmi.close();
    }