java processbuilder windows command wildcard

家住魔仙堡 提交于 2019-12-24 02:32:05

问题


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


来源:https://stackoverflow.com/questions/6069303/java-processbuilder-windows-command-wildcard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!