2013-07-23 226 views
2

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

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”,我会得到相同的结果。

所以,如果在终端为“通心络-o输出INPUTFILE”,其中“通心络”已安装的工具命令,如何写在java吗?我试过

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

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

任何人都可以给我一些建议吗?

编辑:

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

+0

我个人会避免直接使用'Runtime.exec',而是使用'ProcessBuilder'。话虽如此,你应该拆分你的cmd数组,以便每个元素代表一个单独的参数,这个参数将被发送到你正在执行的命令中。你的例子会提示'cd ../ .. && ls'会作为你正在执行的命令的单个参数出现,这不是你想要的 – MadProgrammer

+0

谢谢,madprogrammer。如果是这样,写入cmd1'String [] cmd1 = {“/ bin/sh”, “-c”,“cd ../ ..”,“txl -o output inputFile”}或' String [] cmd1 = {“cd ../ ..”,“txl -o output inputFile”}'?或者你能告诉我如何编写cmd1?谢谢! @MadProgrammer – Eve

+0

我会建议更类似'{“/ bin/sh”,“-c”,“cd”,“../ ..”,“&&”,“txl”,“-o”,“output “,”inputFile“}'但你可能需要试验它 – MadProgrammer

回答

0

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

编辑:

在这种情况下是对所必要的执行壳,只执行cd ../.. && ls是行不通的,因为像cdls之间的&&运营商都没有Java,但通过外壳的理解。

+0

谢谢,摩根。如果是这样,它应该适用于命令“cd ../ .. && txl -o output inputFile”吧?或者java程序只能运行一些默认命令,如ls,cd,dir等? @morgano – Eve

+0

@Eve我修复了我的答案,实际上,如果您尝试仅执行cd ../ .. && ls,您将得不到相同的结果 – morgano

0

你可以找到here什么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执行程序并等待它完成,你可以使用this