gpt4 book ai didi

java - 从 Java 执行未标记化的命令行

转载 作者:行者123 更新时间:2023-11-29 09:46:30 25 4
gpt4 key购买 nike

我目前正在使用 ProcessBuilder 从 Java 服务器运行命令。该服务器将取代旧的 Perl 服务器,我们的许多遗留代码都指定了特定于平台的命令行。

例如,在 Windows 上它可能会这样做:

command -option "hello world"

在 unix 上它可能会这样做:

command -option 'hello world'

问题是 ProcessBuilder 和 Runtime.exec 都采用标记化的命令行(例如,{"command", "-option", "hello world"} 用于 unix 和 windows)。

虽然我更喜欢独立于平台的方式,但我们的代码库中有大约 3000 万行 perl 代码。如果我不为不同的平台编写分词器(真的没什么大不了的,我只是不想做 WTF),有没有办法让操作系统上的 shell 对命令行进行分词?

最佳答案

你能使用重载的Runtime.exec(String)吗?接受单个字符串并将其作为整个命令运行?


以下适用于 Windows:

Process p = Runtime.getRuntime().exec("perl -e \"print 5\"");
System.out.println(IOUtils.toString(p.getInputStream()));
p.destroy();

这或多或少就是 Runtime.exec(String) 正在做的事情:

public static void main(String [] args) throws Exception {
Process p = new ProcessBuilder(getCommand("perl -e \"print 5\"")).start();
System.out.println(IOUtils.toString(p.getInputStream()));
p.destroy();

}

private static String[] getCommand(String input) {
StringTokenizer tokenizer = new StringTokenizer(input);
String[] result = new String[tokenizer.countTokens()];
for (int i = 0; tokenizer.hasMoreTokens(); i++) {
result[i] = tokenizer.nextToken();
}
return result;
}

关于java - 从 Java 执行未标记化的命令行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1980671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com