java 调用linux指令

java 调用linux指令

/**
     * java调用linux指令
     * 执行简单命令 String cmd="ls" int tp = 1 返回执行结果 非1 返回命令执行后的输出
     * @throws UnsupportedEncodingException 
     */

public static String runCommand(String cmd, int tp,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
    response.setContentType("text/html;charset=utf-8");
    request.setCharacterEncoding("utf-8");
    StringBuffer buf = new StringBuffer(1000);
    String rt = "-1";
    try {
        Process pos = Runtime.getRuntime().exec(cmd);
        pos.waitFor();
        if (tp == 1) {
            if (pos.exitValue() == 0) {
                rt = "1";
            }
        } else {
            InputStreamReader ir = new InputStreamReader(pos.getInputStream(),"utf-8");
            LineNumberReader input = new LineNumberReader(ir);
            String ln = "";
            while ((ln = input.readLine()) != null) {
                buf.append(ln + "
"); } rt = buf.toString(); input.close(); ir.close(); } } catch (java.io.IOException e) { rt = e.toString(); } catch (Exception e) { rt = e.toString(); } System.out.println("tr:"+rt); return rt; }

你可能感兴趣的:(Java)