How do I execute the Unix grep
program to search for patt开发者_Go百科erns in a set of files by calling that command from inside a Java program?
You can use Runtime.exec
public Process exec(String[] cmdarray, String[] envp, File dir) throws IOException
Executes the specified command and arguments in a separate process with the specified environment and working directory.
EDIT: As Joachim and andypandy point out, ProcessBuilder
has a more flexible interface, and if you're running on JDK7 or later provides support for setting up sub-process file descriptors.
Starting a new process which uses the default working directory and environment is easy:
Process p = new ProcessBuilder("myCommand", "myArg").start();
Check out the javadoc for java.lang.Runtime#exec and java.lang.ProcessBuilder.
精彩评论