开发者

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

开发者 https://www.devze.com 2023-02-28 23:09 出处:网络
I want to get total RAM on Android: private String getTotalRAM() { ProcessBuilder cmd; String result=\"\";

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 wi开发者_开发技巧th grep, I get nothing. How can i fix this? I just want to get total available RAM at this moment.


All kinds of redirections (|, >, <, ...) are handled by the shell. If you don't invoke the shell, then you can't use those.

A clean solution would be to read /proc/meminfo in your Java code and simple search for the String MemTotal manually. The code wouldn't be much longer than what you're doing now and would need a lot less resurces.


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

精彩评论

暂无评论...
验证码 换一张
取 消