Java runtime exec

2019-08-17 09:28发布

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?

3条回答
太酷不给撩
2楼-- · 2019-08-17 09:37

The alternative is to use the ProcessBuilder class, which has a somewhat cleaner interface, but your main problem is probably related to how the OS processes command lines, and there isn't much Java can do to help you with that.

查看更多
乱世女痞
3楼-- · 2019-08-17 09:47

As noted above, cd is a shell builtin. i.e. 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 (e.g. 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.

查看更多
不美不萌又怎样
4楼-- · 2019-08-17 10:02

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.

查看更多
登录 后发表回答