java: 执行Linux命令,获取结果

package com.css.k3.k3xk.action;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class MyCommandExecutor {
    public static String executeCommand(String command, String parameter) {
        String result = null;
        try {
            String[] commandString = new String[]{"/bin/sh ", " -c ", parameter};
            //String[] commandString = new String[]{command , parameter};
            Process process = Runtime.getRuntime().exec(commandString);
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuffer stringBuffer = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                stringBuffer.append(line).append("\r\n");
            }
            result = stringBuffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

package com.css.k3.k3xk.action;

public class MyTest {


        public static void main(String[] args) {
            String result = MyCommandExecutor.executeCommand("ifconfig ", " ");
            System.out.println("命令执行结果: "+ " " + result);

        }


}

你可能感兴趣的:(JAVA基础,java,linux,python)