如何在java中传递bashscript的参数?

z8dt9xmd  于 2021-06-07  发布在  Kafka
关注(0)|答案(3)|浏览(523)

我有以下命令要通过我的java程序运行;
./kafka-topics.sh--zookeeper zk1.xx。com:2181,zk2.xx号。com:2181,zk3.xx号。com:2181 --delete --主题测试主题
我称这个bash脚本为;

ProcessBuilder builder = new ProcessBuilder(CConstants.KAFKA_TOPIC_SH);
builder.command("--zookeeper","zk1.xx.com:2181,zk2.xx.com:21811,zk3.xx.com:2181",
                "--delete", "--topic", "testTopic");
        builder.start();

但我得到以下错误;

java.io.IOException: Cannot run program "--zookeeper": error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048) ~[?:1.8.0_66]
    at

如何使用参数运行bash脚本?
在这里
--zookeeper,-delet,e--topic是参数
其他的是这些参数

4zcjmb1e

4zcjmb1e1#

调用command方法时,会覆盖传递给processbuilder构造函数的命令。构造函数有一个vararg变量,您也可以在其中传递命令参数:

new ProcessBuilder(CConstants.KAFKA_TOPIC_SH, "--zookeeper",
   "zk1.xx.com:2181,zk2.xx.com:21811,zk3.xx.com:2181", "--delete", "--topic",   "testTopic")
   .start();
n9vozmp4

n9vozmp42#

您可以直接调用kafkaapi,而不是将java命令封装到bash脚本中。例如,
string[]options=新字符串[]{
“--创建”,
“--Zookeeper”,
“zk_host:port",
“--分区”,
"1",
“--主题”,
“测试”,
“--复制因子”,
"1" };
topiccommand.main(选项);

a5g8bdjr

a5g8bdjr3#

您得到的错误显示您的第一个参数被解释为命令名。试试这个:

ProcessBuilder builder = new ProcessBuilder();
builder.command(CConstants.KAFKA_TOPIC_SH,"--zookeeper","zk1.xx.com:2181,zk2.xx.com:21811,zk3.xx.com:2181",
                "--delete", "--topic", "testTopic");
        builder.start();

相关问题