java - 命令行参数中 * 的问题

标签 java command-line-arguments wildcard glob

我用 Java 编写了一个程序,它通过命令行参数接受输入。 我从命令行输入两个数字和一个运算符。 为了将两个数字相乘,我必须给出输入,例如5 3 *,但它没有按写的那样工作。

为什么它不接受来自命令行的*

最佳答案

这是因为 * 是一个 shell 通配符:它对 shell 有特殊的含义,shell 在将其传递给命令之前对其进行扩展(在本例中为 java )。

由于您需要一个文字 *,因此您需要将其从 shell 中转义。确切的转义方式取决于您的 shell,但您可以尝试:

java ProgramName 5 3 "*"

或者:

java ProgramName 5 3 \*
<小时/>

顺便说一句,如果您想知道 shell 对 * 做了什么,请尝试将 String[] args 的内容打印到您的 main 方法。您会发现它将包含目录中文件的名称。

如果您需要传递一些文件名作为命令行参数,这会很方便。

另请参阅

  • Wikipedia: glob

    For example, if a directory contains two files, a.log and b.log then the command cat *.log will be expanded by the shell to cat a.log b.log

  • Wikipedia: Escape character

    In Bourne shell (sh), the asterisk (*) and question mark (?) characters are wildcard characters expanded via globbing. Without a preceding escape character, an * will expand to the names of all files in the working directory that don't start with a period if and only if there are such files, otherwise * remains unexpanded. So to refer to a file literally called "*", the shell must be told not to interpret it in this way, by preceding it with a backslash (\).

关于java - 命令行参数中 * 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2718873/

相关文章:

Java进程立即退出

java - : A single JMS topic with a switch statement, 或个别主题哪个提供更好的性能?

java - 对象和抽象的ArrayList

java - 状态栏颜色不会随 AppCompatActivity 改变

python - 如何使用 Python 的 optparse 格式化位置参数帮助?

haskell - optparse-applicative 子命令帮助文本

java - Java 是否具有与 C# 的 Environment.GetCommandLineArgs() 等效的功能?

java - 为什么 Java 没有 "deep"通配符导入?

java - 在字符串集合中使用通配符搜索

java - 使用 Java 自动提交 HTML 表单以查找杂货店营业时间