zoukankan      html  css  js  c++  java
  • Java调用Linux下的shell命令并将结果以流的形式返回

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

    public class Main
    {
    public static void main(String[] args)
    {

    //得到Java进程的相关Runtime运行对象
    Runtime runtime = Runtime.getRuntime();

    try
    {
    //利用exec()方法执行shell 命令 ls -al /root ,并且返回一个Process对象 也就是子进程
    //ps:这里都以最简单的shell命令举例。
    Process process = runtime.exec("ls -al /root");

    BufferedReader bufferReader = new BufferedReader(
    new InputStreamReader(process.getInputStream()));

    StringBuffer stringBuffer = new StringBuffer();

    String temp = null;

    while ((temp = bufferReader.readLine()) != null)
    {
    stringBuffer.append(temp);

    stringBuffer.append(" ");
    }

    System.out.println(stringBuffer);

    }
    catch (IOException e)
    {
    e.printStackTrace();
    }
    }
    }

    public class ShellExcuter {

     

    private static Logger logger = Logger.getLogger(ShellExcuter.class);

     

    /**

    * 跑linux命令

    * @param cmd

    * @param args

    */

    public static void runShell(String cmd, String[] args) {

    InputStream in;

    BufferedReader br;

    OutputStream out;

    BufferedWriter bw;

    try {

    for (String arg : args) {

    cmd = cmd +" "+arg;

    }

    // String[] cmds = new String[] {

    // "/bin/sh",

    // "-c",

    // cmd };

    logger.info(cmd);

    Process process = Runtime.getRuntime().exec(cmd);

     

    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

    String temp = null;

    while ((temp = bufferReader.readLine()) != null) {

    logger.info(temp);

    }

     

    BufferedReader bufferReader2 = new BufferedReader(new InputStreamReader(process.getErrorStream()));

    while ((temp = bufferReader.readLine()) != null) {

    logger.info(temp);

    }

     

    bufferReader.close();

    bufferReader2.close();

     

    process.waitFor();

    process.destroy();

    } catch (Throwable e) {

    logger.error("执行linux命令出错:" + e.getMessage());

    e.printStackTrace();

    }

    }

     

    }

  • 相关阅读:
    日期格式不合法
    DataGridView的Scrollbar通過編程不能自動下滾
    Sourcesafe shadown backup
    共享目錄突然不工作 
    VS2005編譯后版本如何控制
    WebBrowser用作RichTextBox
    怎樣設定MS Reporting自動橫向列印
    VSS 2005不需登錄,直接開啟的方法
    subreport cannot be shown
    An Algorithm Summary of Programming Collective Intelligence (5)
  • 原文地址:https://www.cnblogs.com/xingchong/p/11698247.html
Copyright © 2011-2022 走看看