Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从JAVA运行bash脚本并返回结果_Java - Fatal编程技术网

从JAVA运行bash脚本并返回结果

从JAVA运行bash脚本并返回结果,java,Java,我正在尝试获取从JAVA程序运行的shell/bash脚本的输出,尽管我运气不好,但代码如下: GetStats(winhostname); public static String winhostname "cmd /c hostname"; public static void GetStats(String operation) { try { Process p=Runtime.getRuntime().e

我正在尝试获取从JAVA程序运行的shell/bash脚本的输出,尽管我运气不好,但代码如下:

GetStats(winhostname);

public static String winhostname "cmd /c hostname";

public static void GetStats(String operation)
    {
         try 
            { 
            Process p=Runtime.getRuntime().exec(operation); 
            p.waitFor(); 
            BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream())); 
            String line=reader.readLine(); 
            while(line!=null) 
            { 
            System.out.println(line);
            if (operation.equals("winhostname"))
            {
                winhostnamevalue = line;
            }
            line=reader.readLine(); 
            } 

            } 
            catch(IOException e1) {} 
            catch(InterruptedException e2) {}       
    }

这在Windows上运行良好,因此我将winhostname的值更改为“sh namecheck.sh”(它只是回显主机名),shell脚本与java/class文件位于同一目录中。虽然运行时我得到一个空结果,不是空的,只是空的。

试试
/bin/sh
。我不确定当您从java运行程序时,它是否拥有使用shell时所拥有的所有环境

如果不起作用,尝试运行一些命令(例如
pwd
)。但是提供完整的路径。然后,当它工作时,请再次尝试您的命令,并确保它可以找到您的脚本。首先使用绝对路径。然后移动到相对路径


祝您好运。

您正在尝试在windows上运行bash shell?@hvgotcodes我希望不会:尝试为您的unix进程获取stderr-它可能会为您指明正确的方向-请参阅进程#getErrorStream()