java processbuilder windows command wildcard

2019-07-18 12:11发布

问题:

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?

回答1:

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);