0

I try to run this shell in java but it never works.

Process p = Runtime.getRuntime().exec(" cat *.java|sed '/import/d'|sed'/package/d'>>b.java ");

When I change the cmd to something like "ls" or "open foo.java" the code will works.

Any idea why?

6
  • (1) What actually happens? Are you getting any error messages? (2) Does your command works directly from the shell? Commented Apr 26, 2013 at 1:47
  • Yes the command fully worked when I type by hand! the error said file dos not exist. Commented Apr 26, 2013 at 1:58
  • Do you run your Java program directly from shell or from some IDE? Commented Apr 26, 2013 at 2:03
  • I try with "cat *.java>>a.java". The error is: cat: *.java>>a.java: No such file or directory Commented Apr 26, 2013 at 2:03
  • I run java from cmd line Commented Apr 26, 2013 at 2:04

2 Answers 2

1

The problem is that the file wildcard pattern is not expanded by a glob. Therefore the pattern is treated literally and the file is not found. You need a shell such as bash to interpret this:

Process p = Runtime.getRuntime().exec(new String[] { 
                   "bash", "-c", 
                   "cat *.java|sed '/import/d'|sed'/package/d'>>b.java" });

Make sure to check the contents of getErrorStream.

Aside: Consider using the more convenient ProcessBuilder which uses a varargs array to build the command String.

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

Comments

0

There are a few problems here.

  1. the *.java part is a glob that is usually expanded by the shell
  2. assembling a pipeline from process to process is also a shell feature
  3. the output redirection is a shell feature

Basically, you really need to invoke a shell to run this type of pipeline. The exec method runs a specific program with arguments. You might be able to get this to work by invoking the shell directly and passing the command line as an argument but I doubt that would work either.

You may have to implement the cat *.java part by enumerating the directory contents and reading each file separately. The open separate Process instances for each of the sed commands and implement the pipeline between them using the input and output streams of the Process instances.

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.