简体   繁体   English

从Java程序运行linux命令txl

[英]running linux command txl from java program

I know we can run a linux terminal command in a java program like following code shows a "ls" command for the home directory. 我知道我们可以在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);
        }

But I have no idea what "/bin/sh" and "-c" mean for? 但是我不知道“ / bin / sh”和“ -c”是什么意思? I searched it online and somebody used "bash" or else. 我在网上搜索它,有人用“ bash”或其他方式。 And if I run the command as "cd ../.. && ls" only, I will get the same result. 而且,如果仅以“ cd ../ .. && ls”运行命令,我将得到相同的结果。

So if there is a command in terminal as "txl -o output inputFile", where "txl" is a tool installed, how to write in in java? 因此,如果终端中有一个命令“ txl -o output inputFile”,其中“ txl”是安装的工具,那么如何用Java编写? I tried 我试过了

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

But could not get the result. 但是无法得到结果。 I add "cd ../.." to go to the home directory first from the working space because txl is installed in the home bin directory. 我添加“ cd ../ ..”首先从工作空间转到主目录,因为txl安装在主bin目录中。

Can anyone give me some suggestions? 谁能给我一些建议?

EDIT: 编辑:

I made a stupid spelling error and the command in this format works! 我犯了一个愚蠢的拼写错误,这种格式的命令有效!

you can find here what every parameter in ls do: 您可以在这里找到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

in order to execute a program in java and wait for it to finish you can use this post 为了在Java中执行程序并等待其完成,您可以使用本文

/bin/sh is a program, this is the shell, the option -c specifies that the following is a command to be executed by the shell (which is the third "line" of your cmd1: cd ../.. && ls ) /bin/sh是一个程序,它是外壳程序,选项-c指定以下内容是要由外壳程序执行的命令(这是cmd1的第三行): cd ../.. && ls

EDIT: 编辑:

In this case is nessesary to execute the shell, executing only cd ../.. && ls won't work, because operators like the && between cd and ls are not understood by Java but by the shell. 在这种情况下,必须执行shell,仅执行cd ../.. && ls行不通的,因为Java不能理解cdls之间的&&类的运算符。

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

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