简体   繁体   English

如何将Bash与Java集成

[英]how to integrate Bash with Java

Can any body help me with how to compile a bash script as part of a java program. 任何机构都可以帮助我如何将bash脚本作为Java程序的一部分进行编译。 I am writing a simple java program that i want to use to invoke bash script commands. 我正在编写一个简单的Java程序,我想使用它来调用bash脚本命令。


my java code looks like the following: 我的Java代码如下所示:

    try{
            Process p = Runtime.getRuntime().exec("myscript.sh"); 
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); 

        String line = null;  

        while ((line = in.readLine()) != null){  
                    System.out.println(line); 
        }  
    }
    catch(IOException e){
        System.out.println(e.getMessage());
    }

and the "mysrcipt.sh" file is a simple script that contains the following lines 而“ mysrcipt.sh”文件是一个简单的脚本,其中包含以下几行


!/bin/bash !/ bin / bash

echo "enter your input followed by [ENTER]:" 回显“输入您的输入,然后按[ENTER]:”

read -e choice 读-e选择

echo $choice 回声$选择


My problem is, the program waits for an input at the read command in the script even if i enter multiple lines and press enter several times. 我的问题是,即使我输入多行并按Enter键几次,程序也会在脚本的read命令中等待输入。

You can use: 您可以使用:

Process p = Runtime.getRuntime().exec("bash_script.sh"); 
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));  
String line = null;  
while ((line = in.readLine()) != null) {  
   // use bash script line output
}  

It would be helpful to see some code showing what you're trying to accomplish. 看到一些代码来说明您要完成的工作会很有帮助。

Executing bash script in Java can be done using something like the following... 在Java中执行bash脚本可以使用以下方法完成...

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("YOUR COMMAND STRING");

List<String> lines = IOUtils.readLines(process.getInputStream());

Runtime.exec() is what you need to execute your bash script, but be aware there are a few pitfalls. Runtime.exec()是执行bash脚本所需要的,但是请注意有一些陷阱。 I found this to be a good article when starting to call external scripts. 当开始调用外部脚本时,我发现是一篇不错的文章。

It is written for a windows platform, but a lot of what is discussed is relevant to *nix as well. 它是为Windows平台编写的,但是讨论的很多内容也与* nix有关。

See also this question . 另请参阅此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM