i need to know if a specific string is contained in a list of files. The list of files is dynamic and i have to check a dynamic list of strings. This must be done in Java to work with the result (true or false). And MS Windows is also a requirement.
I thought about that problem i tried to use the unix way to do this:
find C:/temp | xargs grep import -sl
With GnuWin this works in cmd without any problems. So i tried to convert this into Java language. I read many articles about using Runtime class and ProcessBuilder class. But none of the tips are working. At last i tried the following two code snippets:
String binDir = "C:/develop/binaries/";
List<String> command = new ArrayList<String>();
command.add("cmd");
command.add("/c");
command.add(binDir+"find");
command.add("|");
command.add(binDir+"xargs");
command.add(binDir+"grep");
command.add("import");
command.add("-sl");
ProcessBuilder builder = new ProcessBuilder(command);
builder.directory(new File("C:/temp"));
final Process proc = builder.start();
printToConsole(proc.getErrorStream());
printToConsole(proc.getInputStream());
int exitVal = proc.waitFor();
and
String binDir = "C:/develop/binaries/";
String strDir = "C:/temp/";
String[] command = {"cmd.exe ", "/C ", binDir + "find.exe " + strDir + " | " + binDir + "xargs.exe " + binDir + "grep.exe import -sl" };
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command);
printToConsole(proc.getErrorStream());
printToConsole(proc.getInputStream());
int exitVal = proc.waitFor();
I also tried many other ways to concat the command, but either I get an error message (eg. file not found) or the process never comes back.
My questions:
1. Do you know a better way to do this job?
2. If not: Do you see any error in the code?
3. If not: Do you have another way i should try to run that command?
Thanks in advance.
Java’s support for subprocesses is pretty weak, especially on Windows. Avoid using that API if you don’t really need to.
Instead, this SO question discusses how to replace the
findfor the recursive search, and thegrepshould be easy enough (especially withFileUtil.readLines(…)to help).