本文介绍了如何通过Java程序在新的gnome终端中启动Shell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Java程序运行shell脚本(例如myscript.sh).

I'm trying to run a shell script (say myscript.sh) from a java program.

当我从终端运行脚本时,就像这样:

when i run the script from terminal, like this :

./myscript.sh

它工作正常.

但是当我从Java程序调用它时,使用以下代码:

But when i call it from the java program, with the following code :

try
    {
        ProcessBuilder pb = new ProcessBuilder("/bin/bash","./myScript.sh",someParam);

        pb.environment().put("PATH", "OtherPath");

        Process p = pb.start();

        InputStreamReader isr = new InputStreamReader(p.getInputStream());
        BufferedReader br = new BufferedReader(isr);

        String line ;
        while((line = br.readLine()) != null)
           System.out.println(line);

        int exitVal = p.waitFor();
    }catch(Exception e)
    {  e.printStackTrace();  }
}

它没有相同的方式.几个shell命令(例如sed,awk和类似命令)被跳过,根本不提供任何输出.

It doesnt goes the same way.Several shell commands (like sed, awk and similar commands) get skipped and donot give any output at all.

问题:是否可以使用Java在新的终端中启动此脚本.

Question : Is there some way to launch this script in a new terminal using java.

PS:我发现"gnome-terminal"命令在shell中启动了一个新的终端,但是,我不知道如何在Java代码中使用相同的代码.

PS : i've found that "gnome-terminal" command launches a new terminal in shell, But, i'm unable to figure out, how to use the same in a java code.

我对使用Shell脚本非常陌生.请帮助

i'm quite new to using shell scripting. Please help

预先感谢

推荐答案

在Java中:

import java.lang.Runtime;

class CLI {

    public static void main(String args[]) {
        String command[] = {"/bin/sh", "-c",
                            "gnome-terminal --execute ./myscript.sh"};
        Runtime rt = Runtime.getRuntime();
        try {
            rt.exec(command);
        } catch(Exception ex) {
            // handle ex
        }
    }

}

脚本的内容是:

#!/bin/bash

echo 'hello!'

bash

注意:

  • 您将在后台线程或工作线程中执行此操作
  • shell脚本中的最后一个命令是 bash ;否则执行完成并且终端关闭.
  • shell脚本与调用Java类位于同一路径.
  • You'll do this in a background thread or a worker
  • The last command, in the shell script, is bash; otherwise execution completes and the terminal is closed.
  • The shell script is located in the same path as the calling Java class.

这篇关于如何通过Java程序在新的gnome终端中启动Shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 00:18
查看更多