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

查看:46
本文介绍了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 中使用以下内容时

However when I use the following in Java

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

它返回一个错误:未注册的 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 的半损坏参数解析将首先解析空格(导致像 ("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天全站免登陆