简体   繁体   English

Java运行时执行程序

[英]Java runtime exec

I am trying to do something using system exec in Java 我正在尝试使用Java中的系统执行程序来做某事

Runtime.getRuntime().exec(command);

Surprisingly everything that is related with paths, directories and files is not working well 令人惊讶的是,与路径,目录和文件有关的所有内容均无法正常工作

I don't get why and just want to know is there any alternatives ? 我不明白为什么,只想知道还有其他选择吗?

替代方法是使用ProcessBuilder类,该类的界面更简洁一些,但是您的主要问题可能与OS处理命令行的方式有关,而Java并不能帮助您。

As noted above, cd is a shell builtin. 如上所述,cd是内置的shell。 ie it's not an executable. 即它不是可执行文件。 You can determine this using: 您可以使用以下方法确定此值:

$ which cd
cd: shell built-in command

As it's not a standalone executable, Runtime.exec() won't be able to do anything with it. 由于它不是独立的可执行文件,因此Runtime.exec()将无法对其执行任何操作。

You may be better off writing a shell script to do the shell-specific stuff (eg change the working directory) and then simply execute that shell script using Runtime.exec() . 您最好编写一个Shell脚本来执行特定于Shell的工作(例如,更改工作目录),然后使用Runtime.exec()简单地执行该Shell脚本。 You can set PATH variables etc. within your script and leave Java to simply execute your script. 您可以在脚本内设置PATH变量等,而保留Java以便仅执行脚本。

One thing that catches people out is that you have to consume your script's stdout/stderr (even if you throw it away). 吸引人们注意的一件事是,您必须使用脚本的stdout / stderr(即使将其丢弃)。 If you don't do this properly your process will likely block. 如果您未正确执行此操作,则您的过程可能会阻塞。 See this SO answer for more details. 请参阅此SO答案以获取更多详细信息。

The exec() method can take three arguments. exec()方法可以接受三个参数。 The third is the directory your subprocess should use as its working directory. 第三是子进程应将其用作工作目录的目录。 That solves your "cd" problem, anyway. 无论如何,这解决了您的“ cd”问题。

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

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