windows java processbuilder windows命令通配符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6069303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java processbuilder windows command wildcard
提问by Blue Sky
I want to invoke a Windows command from Java.
我想从 Java 调用 Windows 命令。
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.
但是它不起作用并且Java控制台中没有输出。
What's the solution?
解决办法是什么?
回答by Matthew Murdoch
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.
find
由于路径名中的双正斜杠,它似乎返回了一个错误。如果您将它们更改为反斜杠(加倍以在 Java 字符串中对它们进行转义),则它会成功。
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:
您可以find
使用类似于以下的代码检查错误输出和退出代码(成功时为 0,出现错误时为 1):
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);