Here you can find the source of splitCommand(String command)
Parameter | Description |
---|---|
command | the original command line from a shell |
public static String[] splitCommand(String command)
//package com.java2s; //License from project: Apache License import java.util.ArrayList; public class Main { /**/*w w w. ja v a 2 s .c o m*/ * Split a command line into an argument array. This routine * segments the given command line by whitespace characters * with the exception that strings between double quotation * marks are considered to be single arguments, and will not * be split. * * @param command the original command line from a shell * * @return argument array split from command * */ public static String[] splitCommand(String command) { char[] commandCharArr = command.toCharArray(); int idx = 0; int beginPos = 0; int endPos = 0; char ch = ' '; /* * Quote Matching State: * 0: Start * 1: Left double quotation mark found * 2: Right double quotation mark found */ int state = 0; String argument = ""; ArrayList<String> argList = new ArrayList<String>(); while (idx < commandCharArr.length) { ch = commandCharArr[idx]; // System.out.print(ch); if (ch == '"' && state == 0) { // Left double quotation mark is found beginPos = idx + 1; state = 1; } else if (ch == '"' && state == 1) { // Right double quotation mark is found state = 2; } else if (ch == ' ') { if (state == 2) { // Right double quotation mark has already been found endPos = idx - 1; state = 0; } else if (state == 1) { // Between left and right quotation marks idx++; continue; } else { endPos = idx; } argument = command.substring(beginPos, endPos).trim(); if (!argument.isEmpty()) argList.add(argument); // System.out.println(); while (idx < commandCharArr.length && commandCharArr[idx] == ' ') { idx++; } if (idx == commandCharArr.length) break; beginPos = idx; continue; } else if (idx == commandCharArr.length - 1) { endPos = idx + 1; argument = command.substring(beginPos, endPos).trim(); if (!argument.isEmpty()) argList.add(argument); break; } idx++; } return argList.toArray(new String[argList.size()]); } }