简体   繁体   中英

Java runtime exec

I am trying to do something using system exec in 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. 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.

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() . You can set PATH variables etc. within your script and leave Java to simply execute your script.

One thing that catches people out is that you have to consume your script's stdout/stderr (even if you throw it away). If you don't do this properly your process will likely block. See this SO answer for more details.

The exec() method can take three arguments. The third is the directory your subprocess should use as its working directory. That solves your "cd" problem, anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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