Running Bash commands in Java

后端 未结 7 1362
名媛妹妹
名媛妹妹 2020-11-30 06:03

I have the following class. It allows me to execute commands through java.

public class ExecuteShellCommand {

public String executeCommand(String command) {         


        
7条回答
  •  情书的邮戳
    2020-11-30 06:14

    You could use the bash command "pmset -g batt" like in the method bellow witch returns the battery percentage

    public int getPercentage() {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec("pmset -g batt");
        } catch (IOException e) {
            e.printStackTrace();
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                process.getInputStream()));
        String s = null;
        String y = "";
        while (true) {
            try {
                if (!((s = reader.readLine()) != null)) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            y += s;
            System.out.println("Script output: " + s);
        }
        return Integer.parseInt(y.substring(y.indexOf(')') + 2, y.indexOf('%')));
    }
    

提交回复
热议问题