如何在Windows 10环境中从Java运行在Ubuntu上用Bash编写的shell脚本?

时间:2017-12-09 21:05:23

标签: java windows bash ubuntu

如何在Windows 10环境下从Java运行在Ubuntu上用Bash编写的shell脚本?
我尝试使用此代码,但它没有运行也没有执行脚本。

    public static void main(String[] args) throws IOException {
        Runtime rt = Runtime.getRuntime();
        ProcessBuilder builder = new ProcessBuilder(
            "bash.exe", "/mnt/d/Kaldi-Java/kaldi-trunk/tester.sh");

        Process p = builder.start();
        BufferedReader r = new BufferedReader(new 
        InputStreamReader(p.getInputStream()));
        String line;
        while (true) {
            line = r.readLine();
            if (line != null) {  System.out.print(line);}
            else{break;}   
        }
    }

2 个答案:

答案 0 :(得分:0)

首先:您是否尝试从命令行执行此命令?如果你这样做了,那就意味着问题不在windows上的bash上,而在于你的java程序。

如果无法从命令行执行,请先解决此问题

我无法测试我的程序,因为我使用Ubuntu但可以建议你尝试这样的smth :(等到程序结束)

public class Main {

    public static void main(String[] args) throws IOException, InterruptedException {
        ProcessBuilder builder = new ProcessBuilder(
                "bash.exe", "/mnt/d/Kaldi-Java/kaldi-trunk/tester.sh");

        Process p = builder.start();

        /* waitFor() method stops current thread until this process is over */
        p.waitFor();
        // I think that scanner is a nicer way of parsing output
        Scanner scanner = new Scanner(p.getInputStream());
        while (scanner.hasNextLine()) {
            // you do not have to create `line` outside the loop
            // it does not change performance of a program
            String line = scanner.nextLine();
            System.out.println(line);
        }
    }
}

答案 1 :(得分:0)

如果您尝试在Windows环境中使用Java运行脚本,我建议以不同方式执行它。

我根据这里提出的一个宝贵问题改编了你的代码:

How to run Unix shell script from Java code?

此外,这个问题可以帮助您解决问题: Unable to read InputStream from Java Process (Runtime.getRuntime().exec() or ProcessBuilder)

public static void main(String[] args) throws IOException {

    Process proc = Runtime.getRuntime().exec(
            "/mnt/d/Kaldi-Java/kaldi-trunk/tester.sh"); 
    BufferedReader read = new BufferedReader(
            new InputStreamReader(proc.getInputStream()));

    while (read.ready()) 
    {
        System.out.println(read.readLine());
    }

}

我相信这就是你要找的东西。我相信您的Java代码有点过时,这些编辑应该对您有所帮助。构建java可执行文件后,您可以通过Window的命令提示符运行它。