0

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?

6
  • 1
    tell us what you are trying to do. then only we can give proper help Commented Jun 27, 2012 at 9:21
  • 2
    "Runtime.getRuntime().exec(command); Surprisingly.." Not to me. See When Runtime.exec() won't. Also, for better help sooner, post an SSCCE. Commented Jun 27, 2012 at 9:23
  • Why not use J2SE classes and methods for accessing the file-system? Commented Jun 27, 2012 at 9:24
  • 1
    cd is not going to work. That is not an executable, that is a function of your shell. Commented Jun 27, 2012 at 9:25
  • @Thilo Thanks! what is the alternative of cd Commented Jun 27, 2012 at 9:31

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

well, thanks. I'll try to figure it out. shell script isn't a good idea I need streams
Can you elaborate re. your streams comment ?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.