我有一个程序通过 Runtime.getRuntime().exec(cmdArray[]) 执行命令。用户可以通过在文本框中输入这些命令来为这些命令附加额外的开关。
例子:
cmdArray[] = {"someprogram", "--something", "123"} //this is the initial command
//textbox is -A "bla bla bla" notice the quotes
//do something...
cmdArray[] = {"someprogram", "--something", "123", "-A", "bla bla bla"} //parsed array
是否有一个 java 函数可以让我这样做?还是我必须自己写(听起来很乏味,因为我必须处理单引号和双引号,所有转义等等......)?
谢谢
编辑:不想要额外的依赖,所以我写了一个简单的方法,它没有涵盖所有内容,但它做了我想要的
public String[] getCmdArray(String cmd) { // Parses a regular command line and returns it as a string array for use with Runtime.exec()
ArrayList<String> cmdArray = new ArrayList<String>();
StringBuffer argBuffer = new StringBuffer();
char[] quotes = {'"', '\''};
char currentChar = 0, protect = '\\', separate = ' ';
int cursor = 0;
cmd = cmd.trim();
while(cursor < cmd.length()) {
currentChar = cmd.charAt(cursor);
// Handle protected characters
if(currentChar == protect) {
if(cursor + 1 < cmd.length()) {
char protectedChar = cmd.charAt(cursor + 1);
argBuffer.append(protectedChar);
cursor += 2;
}
else
return null; // Unprotected \ at end of cmd
}
// Handle quoted args
else if(inArray(currentChar, quotes)) {
int nextQuote = cmd.indexOf(currentChar, cursor + 1);
if(nextQuote != -1) {
cmdArray.add(cmd.substring(cursor + 1, nextQuote));
cursor = nextQuote + 1;
}
else
return null; // Unprotected, unclosed quote
}
// Handle separator
else if(currentChar == separate) {
if(argBuffer.length() != 0)
cmdArray.add(argBuffer.toString());
argBuffer.setLength(0);
cursor++;
}
else {
argBuffer.append(currentChar);
cursor++;
}
}
if(currentChar != 0) // Handle the last argument (doesn't have a space after it)
cmdArray.add(argBuffer.toString());
return cmdArray.toArray(new String[cmdArray.size()]);
}
public boolean inArray(char needle, char[] stack) {
for(char c : stack)
if(needle == c)
return true;
return false;
}