java processbuilder windows command wildcard
Asked Answered
L

1

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?

Luci answered 20/5, 2011 at 8:25 Comment(3)
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.Fermi
Hi Mat, It works fine if i paste this directly in the command prompt and run it.Luci
Well, This works in the command line, C:\Workspace>find "searchstr" C://Workspace//*.txtLuci
F
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);
Fermi answered 20/5, 2011 at 12:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.