title: Split a string containing command-line parameters into a String[] in Java
body: <p>Similar to <a href="https://stackoverflow.com/questions/298830/split-string-containing-command-line-parameters-into-string-in-c">this thread for C#</a>, I need to split a string containing the command line arguments to my program so I can allow users to easily run multiple commands.  For example,  I might have the following string:</p>
  
  <pre><code>-p /path -d "here's my description" --verbose other args
  </code></pre>
  
  <p>Given the above, Java would normally pass the following in to main:</p>
  
  <pre><code>Array[0] = -p
  Array[1] = /path
  Array[2] = -d
  Array[3] = here's my description
  Array[4] = --verbose
  Array[5] = other
  Array[6] = args
  </code></pre>
  
  <p>I don't need to worry about any shell expansion, but it must be smart enough to handle single and double quotes and any escapes that may be present within the string. Does anybody know of a way to parse the string as the shell would under these conditions?</p>
  
  <p><strong>NOTE</strong>: I do <strong>NOT</strong> need to do command line parsing, I'm already using <a href="http://jopt-simple.sourceforge.net/examples.html" rel="noreferrer">joptsimple</a> to do that.  Rather, I want to make my program easily scriptable.  For example, I want the user to be able to place within a single file a set of commands that each of which would be valid on the command line.  For example, they might type the following into a file:</p>
  
  <pre><code>--addUser admin --password Admin --roles administrator,editor,reviewer,auditor
  --addUser editor --password Editor --roles editor
  --addUser reviewer --password Reviewer --roles reviewer
  --addUser auditor --password Auditor --roles auditor
  </code></pre>
  
  <p>Then the user would run my admin tool as follows:</p>
  
  <pre><code>adminTool --script /path/to/above/file
  </code></pre>
  
  <p><code>main()</code> will then find the <code>--script</code> option and iterate over the different lines in the file, splitting each line into an array that I would then fire back at a joptsimple instance which would then be passed into my application driver.</p>
  
  <p>joptsimple comes with a Parser that has a <a href="http://jopt-simple.sourceforge.net/apidocs/joptsimple/OptionParser.html#parse(java.lang.String...)" rel="noreferrer">parse method</a>, but it only supports a <code>String</code> array.  Similarly, the <a href="http://opendap.org/api/javaDocs/gnu/getopt/Getopt.html" rel="noreferrer">GetOpt</a> constructors also require a <code>String[]</code> -- hence the need for a parser.</p>