如何使用Java运行带有通配符的unix / shell命令? [英] How to run unix / shell commands with wildcards using Java?

查看:113
本文介绍了如何使用Java运行带有通配符的unix / shell命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Java 中运行一些 unix / shell 命令并处理输出。我使用 getRuntime.exec(),但它没有为某些命令提供正确的输出,例如 ls directory_path / * .tar.gz 。对于该命令,我的程序没有给出任何输出,但它给出错误说没有这样的文件或目录。但是相同的命令在命令提示符下提供正确的输出。

I want to run some unix/shell commands in Java and process the output. I used getRuntime.exec(), but it is not giving correct output for some commands like ls directory_path/*.tar.gz . For that command my program is not giving any output but it is giving error saying No such file or directory. But the same command is giving correct output on command prompt.

有没有其他方法可以执行包含Java中通配符的命令?

Is there any other way to execute commands which include wildcards in Java?

推荐答案


还有其他方法可以执行包含Java中通配符的命令吗?

Is there any other way to execute commands which include wildcards in Java?

是的。

您的代码中有三个潜在问题:

You have three potential problems in your code:


  1. 假设您想要查看外部命令的输出,您需要处理它产生的输出,并自行打印。

  1. Assuming you want to see the output of the external command you need to take care of the output it produces, and print it yourself.

按照我在此提供的示例:

Follow the example I've provided over here:

如果您天真地通过运行时, * 的shell扩展不起作用。 exec 。你必须明确地通过 / bin / bash

The shell expansion of * doesn't work if you naively go through Runtime.exec.You have to go through /bin/bash explicitly.

如果您尝试列出 directory_path / *。tar.gz 的内容,您应该知道(如果您没有以 / <开头/ code>) directory_path 将相对于当前工作目录进行解析。首先尝试给出确定它有效的绝对路径,然后尝试弄清楚为什么它找不到相对路径。

If you try to list the content of directory_path/*.tar.gz you should know that (if you're not starting with a /) directory_path will be resolved relative to the current working directory. Try at first to give the absolute path to make sure it works, and then try to figure out why it can't find the relative path.

以下是一个应该有效的完整示例:

Here's a complete example that should work:

Process proc = new ProcessBuilder("/bin/bash", "-c",
                                  "ls /.../directory_path/*.tar.gz").start();

Reader reader = new InputStreamReader(proc.getInputStream());
int ch;
while ((ch = reader.read()) != -1)
    System.out.print((char) ch);
reader.close();

这篇关于如何使用Java运行带有通配符的unix / shell命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆