2

I want to invoke a Windows command from Java.

Using the following line works fine:

ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C",
      "find \"searchstr\" C://Workspace//inputFile.txt");

But I want to find the string in all text files under that location, tried it this way,

ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C",
      "find \"searchstr\" C://Workspace//*.txt");

But it does not work and there is no output in the Java console.

What's the solution?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Blue Sky
  • 807
  • 1
  • 15
  • 36
  • Does `find "searchstr" C://Workspace//*.txt` work from the windows command prompt? If the path doesn't exist it gives me a 'File not found' message in the first case but with the wildcard it hangs. – Matthew Murdoch May 20 '11 at 08:59
  • Hi Mat, It works fine if i paste this directly in the command prompt and run it. – Blue Sky May 20 '11 at 09:05
  • Well, This works in the command line, C:\Workspace>find "searchstr" C://Workspace//*.txt – Blue Sky May 20 '11 at 09:19

1 Answers1

3

It looks like find is returning an error due to the double forward slashes in the path name. If you change them to backslashes (doubled to escape them in the Java string) then it succeeds.

You can examine the error output and the exit code from find (which is 0 for success and 1 in the case of an error) by using code similar to the following:

ProcessBuilder pb = new ProcessBuilder(
    "cmd.exe", 
    "/C",
    "find \"searchstr\" C://Workspace//inputFile.txt");

Process p = pb.start();
InputStream errorOutput = new BufferedInputStream(p.getErrorStream(), 10000);
InputStream consoleOutput = new BufferedInputStream(p.getInputStream(), 10000);

int exitCode = p.waitFor();

int ch;

System.out.println("Errors:");
while ((ch = errorOutput.read()) != -1) {
    System.out.print((char) ch);
}

System.out.println("Output:");
while ((ch = consoleOutput.read()) != -1) {
    System.out.print((char) ch);
}

System.out.println("Exit code: " + exitCode);
Matthew Murdoch
  • 30,874
  • 30
  • 96
  • 127