Java运行时exec()无法正确转义字符 [英] Java Runtime exec() fails to escape characters properly

查看:597
本文介绍了Java运行时exec()无法正确转义字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能已经回答了,但是是关于unicode,我不认为这是unicode(它是在ASCII所以...)。

This might already been answered before but that was regarding unicode and I don't think this is unicode (it's in ASCII so...).

在我的终端执行这里没有什么问题。

When I execute this in my terminal there is no problem what so ever

vboxmanage setextradata "Test Machine" "VBoxInternal/Devices/pcnet/0/LUN#0/Config/ssh/HostPort" 2222

但是当我在Java

Runtime.getRuntime().exec("vboxmanage setextradata \"Test Machine\" \"VBoxInternal/Devices/pcnet/0/LUN#0/Config/ssh/HostPort\" 2222");

它返回错误:unregistered vm'TestMachine'

It returns an error: unregistered vm '"TestMachine"'

对于带有空格的参数,如Test\ Machine,它也不会转义空格。

The same goes for parameters with spaces in them like Test\ Machine, then it doesn't escape the space.

与字符编码有关,但我没有看到任何选项来设置o_O

Now I think this has something to do with the character encoding, but I don't see any option to set that o_O

推荐答案

和它的参数在一个通过,它有效地把整个字符串推入处理环境(希望最好的)。

You are calling the program and its arguments in one pass, which effectively shoves the entire string into the processing environment (hoping for the best).

在Windows系统中,操作系统以不同的方式处理可执行文件和参数,并将它们全部放在同一个字符串中只需要选择一个完美的字符串,环境(我知道它有两个)可以重新解析为参数列表。更好的解决方案是使用

In Windows systems, the operating system makes a point of handling the executable and arguments differently, and putting them all in the same string just requires you to pick the perfect string which the environment (of which there are two that i know about) can re-parse into an argument list. The better solution is to use

Runtime.exec(new String[] {"vboxmanage", "setextradata", "Test Machine", "VBoxInternal/Devices/pcnet/0/LUN#0/Config/ssh/HostPort", "2222"});

对应于 Runtime的

public Process exec(String[] cmdarray)
         throws IOException

最好的情况下,使用一个字符串方法,你最终会发现如何提示和转义参数,所以它们不会被视为可执行文件名的一部分,但是你会遇到一个新的问题,他们将所有作为一个参数传递给可执行文件。一旦你解决这个问题,根据环境,你会发现你的引号没有从参数剥离(导致参数像2222)或Window的半破解参数解析将首先解析whitespace(导致像(Test)这样的参数,这是没有意义的,这就是为什么有多个 exec 方法可用。

At best, with the one string method you'll eventually find out how to hint and escape out the arguments so they don't get treated as part of the executable name, but then you'll encounter a new issue, that they get passed all as one parameter to the executable. Once you fix that depending on the environment, you'll either find that your quotes aren't getting stripped from the parameters (leading to parameters like "2222") or that Window's semi-broken argument parsing is going to parse on whitespace first (leading to parameters like ("Test). It doesn't make sense, that's why there are more than one exec methods available.

这篇关于Java运行时exec()无法正确转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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