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

查看:54
本文介绍了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).

要按照您想要的方式拆分字符串,请使用接受字符串数组的 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天全站免登陆