问题如下:
现在是windows环境,我在电脑D盘下有个1.bat文件,代码如下:
echo "success..."
exit 100java代码如下:
String shell = "cmd /c start D:/1.bat ";
Runtime rt = Runtime.getRuntime();现在可以把1.bat调起来,但是我想在java程序中获取1.bat最后返回的100,求教各位高手,小弟不甚感激。同时,当换成unix环境时,我的java程序要执行的是shell脚本,获取返回值的方法是否一样?求各位大神指点...Javashell脚本

解决方案 »

  1.   

    String shell = "cmd /c start D:/1.bat ";将Start去掉,1.bat是批处理,作为cmd的子进程运行,相对于所编写的程序对应的进程来说,就变成了孙子进程,而不是儿子进程。
    我的测试代码:
    try
    {
    String shell = "cmd /c D:/1.bat ";
    Process proc = Runtime.getRuntime().exec(shell);
    proc.waitFor();
    System.out.println(proc.exitValue());
    }
    catch (Exception e)
    {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    其中,proc.exitValue()就是你的要的返回值;Unix环境下调用方法大致是一样的;
    更进一步,你还可以通过proc.getInputStream()和proc.getErrorStream()获取批处理在控制台中输出的内容,如下所示:
    try
    {
    String shell = "cmd /c D:/1.bat ";
    Process proc = Runtime.getRuntime().exec(shell);
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    proc.getInputStream()));
    String line = null;
    while ((line = reader.readLine()) != null)
    {
    System.out.println(line);
    Thread.sleep(2000);
    }
    BufferedReader error = new BufferedReader(new InputStreamReader(
    proc.getErrorStream()));
    while ((line = error.readLine()) != null)
    {
    System.out.println(line);
    }
    proc.waitFor();

    }
    catch (Exception e)
    {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }