java processbuilder Windows 命令通配符

发布于 2024-11-08 18:55:54 字数 411 浏览 4 评论 0原文

我想从 Java 调用 Windows 命令。

使用以下行工作正常:

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

但我想在该位置下的所有文本文件中找到该字符串,尝试了这种方式,

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

但它不起作用,并且 Java 控制台中没有输出。

解决办法是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

同尘 2024-11-15 18:55:54

由于路径名中存在双正斜杠,find 似乎返回了错误。如果将它们更改为反斜杠(加倍以在 Java 字符串中转义它们),那么它就会成功。

您可以使用类似于以下的代码检查 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);

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文