2

我知道我们可以在 java 程序中运行 linux 终端命令,如下代码显示主目录的“ls”命令。

String[] cmd1 =  {
        "/bin/sh",
        "-c",
        "cd ../.. && ls"};
        Process child1 = Runtime.getRuntime().exec(cmd1);
        child1.waitFor();

final BufferedReader is = new BufferedReader(new InputStreamReader(child1.getInputStream()));
        String line;
        while ((line = is.readLine()) != null) {

            System.out.println("output is: "+line);
        }

但我不知道“/bin/sh”和“-c”是什么意思?我在网上搜索了它,有人使用了“bash”或其他。如果我只将命令作为“cd ../.. && ls”运行,我将得到相同的结果。

那么如果终端中有一个命令为“txl -o output inputFile”,其中“txl”是安装的工具,如何在java中写入?我试过

String[] cmd1 =  {
        "/bin/sh",
        "-c",
        "cd ../.. && txl -o output inputFile"};

但无法得到结果。我添加“cd ../..”以首先从工作空间进入主目录,因为 txl 安装在主 bin 目录中。

谁能给我一些建议?

编辑:

我犯了一个愚蠢的拼写错误,这种格式的命令有效!

4

2 回答 2

0

你可以在这里找到ls 中每个参数的作用:

-c
 with -lt: sort by, and show, ctime (time of last modification of file status information) with -l: show ctime and sort by name otherwise: sort by ctime

为了在java中执行一个程序并等待它完成你可以使用这篇文章

于 2013-07-23T11:06:17.590 回答
0

/bin/sh是一个程序,这是shell,该选项-c指定以下是要由shell执行的命令(这是你的cmd1的第三“行” cd ../.. && ls:)

编辑:

在这种情况下,必须执行 shell,只执行是cd ../.. && ls行不通的,因为像&&betweencd和这样的运算符ls不是 Java 可以理解的,而是 shell 可以理解的。

于 2013-07-23T11:06:55.737 回答