CommandLineUtils { public static void addEscapedArgumentOnWindows(StringBuilder buffer, String arg) { if (buffer.length() > 0) buffer.append(' '); boolean quoted = false; Matcher matcher = RE_W.matcher(arg); while (matcher.find()) { String matched = matcher.group(); char c = matched.charAt(0); if (c == '%') { if (quoted) { if (buffer.charAt(buffer.length() - 1) == '\\') buffer.append('\\'); buffer.append('"').append(matched); quoted = false; } else { buffer.append(matched); } } else { if (!quoted) { buffer.append('"'); quoted = true; } if (c == '"') buffer.append('\\'); buffer.append(matched); } } if (quoted) { if (buffer.charAt(buffer.length() - 1) == '\\') buffer.append('\\'); buffer.append('"'); } } private  CommandLineUtils(); static void addEscapedArgumentOnWindows(StringBuilder buffer, String arg); static void addEscapedArgumentOnUnix(StringBuilder buffer, String arg); static String espaceCommandLineArgs(String[] args);  }
@Test public void testWin() { StringBuilder buffer; buffer = new StringBuilder(); addEscapedArgumentOnWindows(buffer, "abc"); assertThat(buffer.toString(), is("\"abc\"")); buffer = new StringBuilder(); addEscapedArgumentOnWindows(buffer, "a\\b\\c"); assertThat(buffer.toString(), is("\"a\\b\\c\"")); buffer = new StringBuilder(); addEscapedArgumentOnWindows(buffer, "a\\b\\c\\"); assertThat(buffer.toString(), is("\"a\\b\\c\\\\\"")); buffer = new StringBuilder(); addEscapedArgumentOnWindows(buffer, "%abc%"); assertThat(buffer.toString(), is("%\"abc\"%")); buffer = new StringBuilder(); addEscapedArgumentOnWindows(buffer, "%a\\b\\c\\%"); assertThat(buffer.toString(), is("%\"a\\b\\c\\\\\"%")); }