Java tutorial
//package com.java2s; //License from project: Open Source License import java.io.IOException; import java.io.StringReader; import java.util.List; import java.util.Vector; public class Main { /** * Takes a single line command as a string and breaks it up in tokens * acceptable for the java.lang.ProcessBuilder.ProcessBuilder * @param command Complete command as a single string * @return Array of strings that are acceptable tokens for ProcessBuilder * @throws Exception */ static public List<String> breakUpCommand(String command) throws Exception { try { List<String> commandTokens = new Vector<String>(); StringBuilder currentToken = null; boolean isTokenQuoted = false; StringReader sr = new StringReader(command); int b = sr.read(); while (b >= 0) { char c = (char) b; if (null == currentToken) { // At token is not in progress // Skipping spaces if (' ' == c || '\t' == c) { } else if ('"' == c) { // Starting a quoted token currentToken = new StringBuilder(); //currentToken.append(c); isTokenQuoted = true; } else { // Starting a non-quoted token currentToken = new StringBuilder(); currentToken.append(c); isTokenQuoted = false; } } else if (isTokenQuoted) { // A quoted token is in progress. It ends with a quote if ('"' == c) { //currentToken.append(c); String token = currentToken.toString(); currentToken = null; commandTokens.add(token); } else { // Continuation currentToken.append(c); } } else { // A non-quoted token is in progress. It ends with a space if (' ' == c || '\t' == c) { String token = currentToken.toString(); currentToken = null; commandTokens.add(token); } else { // Continuation currentToken.append(c); } } b = sr.read(); } if (null != currentToken) { String token = currentToken.toString(); commandTokens.add(token); } return commandTokens; } catch (IOException e) { throw new Exception("Error while breaking up command into tokens: " + command, e); } } }