Linux上的Java Runtime.exec()参数 [英] Java Runtime.exec() arguments on Linux

查看:499
本文介绍了Linux上的Java Runtime.exec()参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这是问题所在: 我有3个类MyClass1和MyClass2和ExecClass. 我进入命令提示符并执行以下操作:

Okay so here is the problem: I have 3 classes MyClass1 and MyClass2 and ExecClass. I go to my command prompt and do this:

$java MyClass1 -exec "java MyClass2 arg1 arg2"

效果很好. 现在在ExecClass中,我有以下一行:

which works perfectly. Now in ExecClass I have the following line:

Runtime.getRuntime().exec("java MyClass1 -exec \"java MyClass2 arg1 arg2\"");

问题是,如果您打印第二个字符串,它与第一个字符串完全相同,但是当我的ExecClass运行它时,MyClass1会抱怨:无法识别的参数arg1失败. 经过一番调试后,我发现在第一种情况下,当我直接从终端调用时,引号中的整个字符串是1个参数(arg [1]),在第二种情况下,arg.length = 5且它基本上将它们分割了...出于某种未知的原因. 我只需要知道一个工作环境,如果有人知道,也可以运行我的Runtime.exec()即可. PS:在我的Windows计算机上,这种问题仅在linux上不会发生.这是一个Ubuntu破坏内核:2.6.32-279.14.1.el6.x86_64.

Problem is if you print the second string its exactly the same as the first, but when my ExecClass runs it MyClass1 complains: Unrecognized argument arg1 and fails. After a bit of debugging I found out that in the first case when I'm calling directly from the terminal the whole string in the quotes is 1 argument (arg[1]), where in the second case the arg.length = 5 and it basically splits them... for some unkown reason to me. I just need to know a workarround that if someone knows, aka my Runtime.exec() to works. PS: On my Windows machine such problem does not occur only on the linux. It's a ubuntu destrution Kernel: 2.6.32-279.14.1.el6.x86_64.

推荐答案

Runtime.exec与其他语言中类似system()的函数不同,它不会调用shell来解析命令(并且双引号字符串是shell的功能) ).

Runtime.exec, unlike system()-like functions in other languages, does not invoke a shell to parse the command (and double quoted strings are a shell feature).

要按所需方式拆分字符串,请使用接受String数组的Runtime.exec:

To split the string the way you want it, use the Runtime.exec that accepts a String array:

Runtime.getRuntime().exec(new String[] { "java", "MyClass1", "-exec", "java MyClass2 arg1 arg2"});

这篇关于Linux上的Java Runtime.exec()参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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