在java中运行cmd-line失败 [英] Run cmd-line in java fails

查看:143
本文介绍了在java中运行cmd-line失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临以下问题:



我在Eclipse中编写一个java应用程序。在我的应用程序内我想要启动一个cmd命令:

  C:/ Users / User1 / Content- / bin / connect -h 

命令connect -h是一个企业内部应用程序,精细。
如果我使用命令行a将不得不使我的当前目录像这样:

  cd C:用户/用户1 /内容集成测试框架/ JDBC连接器/ bin / 

connect -h
这很好。但我真的不知道如何在一个java应用程序中执行这个命令。



这里他们告诉我如何在java应用程序中运行cmd:
< a href =http://stackoverflow.com/questions/4884681/how-to-use-cd-command-using-java-runtime>如何使用cd



但是如果我这样做:

  Runtime.getRuntime()。exec('C:/ Users / User1 / Content-Integration Testing Framework / JDBC Connector / bin / connect'-h); 

Eclipse告诉我:

  java.io.IOException:无法运行程序'C:/ Users / User1 / Content-Integration:CreateProcess error = 2,Das System kann die angegebene Datei nicht finden 
at java。 lang.ProcessBuilder.start(未知源)

它在内容集成 / p>

有人可以帮我吗?

解决方案

exec() 通过 String 数组接受多个参数



Runtime.exec(String s)将使用tokenizer拆分字符串(这就是为什么引用字符串不工作,以及为什么你看到你所做的行为)。如果你自己解析可执行文件和参数,并传递每个作为数组元素在上面例如

  String [] args = new String [] {executable,arg1,arg2}; 
Runtime.getRuntime()。exec(args); //不要忘记收集stdout / err等

那么你会绕过 Runtime.exec(String s)的拆分行为。


I am facing the following problem:

I am writing a java-application in Eclipse. Inside my application I want to start a cmd command:

C:/Users/User1/Content-Integration Testing Framework/JDBC Connector/bin/connect -h

The command 'connect -h' is a an enterprise internal application which works fine. If I would use a comand line a would have to chance my current directory like that:

cd C:/Users/User1/Content-Integration Testing Framework/JDBC Connector/bin/

and afterwards I would just type connect -h This works great. But I am not really shure how to execute this command within a java application.

Here they tell me how to run a cmd inside a java application: How to use "cd" command using java runtime?

But if I do that:

Runtime.getRuntime().exec("'C:/Users/User1/Content-Integration Testing Framework/JDBC Connector/bin/connect' -h");

Eclipse tells me:

java.io.IOException: Cannot run program "'C:/Users/User1/Content-Integration": CreateProcess error=2, Das System kann die angegebene Datei nicht finden
    at java.lang.ProcessBuilder.start(Unknown Source)

It cuts my command at "Content-Integration".

can someone help me please?

解决方案

You should use the version of exec() that takes multiple args via a String array.

Runtime.exec(String s) will split your string using a tokenizer (this is why quoting the string won't work, and why you see the behaviour you do). If you resolve the executable and arguments yourself, and pass each as an array element in the above e.g.

String[] args = new String[]{"executable", "arg1", "arg2"};
Runtime.getRuntime().exec(args); // don't forget to collect stdout/err etc.

then you will bypass Runtime.exec(String s)'s splitting behaviour.

这篇关于在java中运行cmd-line失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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