Java String Quote quoteForBatchScript(String arg)

Here you can find the source of quoteForBatchScript(String arg)

Description

Quote a command argument for a command to be run by a Windows batch script, if the argument needs quoting.

License

Apache License

Declaration

static String quoteForBatchScript(String arg) 

Method Source Code

//package com.java2s;
/*//from   ww w . j  av  a2  s .c o m
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
     * Quote a command argument for a command to be run by a Windows batch script, if the argument
     * needs quoting. Arguments only seem to need quotes in batch scripts if they have certain
     * special characters, some of which need extra (and different) escaping.
     *
     *  For example:
     *    original single argument: ab="cde fgh"
     *    quoted: "ab^=""cde fgh"""
     */
    static String quoteForBatchScript(String arg) {

        boolean needsQuotes = false;
        for (int i = 0; i < arg.length(); i++) {
            int c = arg.codePointAt(i);
            if (Character.isWhitespace(c) || c == '"' || c == '=' || c == ',' || c == ';') {
                needsQuotes = true;
                break;
            }
        }
        if (!needsQuotes) {
            return arg;
        }
        StringBuilder quoted = new StringBuilder();
        quoted.append("\"");
        for (int i = 0; i < arg.length(); i++) {
            int cp = arg.codePointAt(i);
            switch (cp) {
            case '"':
                quoted.append('"');
                break;

            default:
                break;
            }
            quoted.appendCodePoint(cp);
        }
        if (arg.codePointAt(arg.length() - 1) == '\\') {
            quoted.append("\\");
        }
        quoted.append("\"");
        return quoted.toString();
    }
}

Related

  1. quoteEach(String string)
  2. quoteEscape(final String original)
  3. quoteEscaped(String input)
  4. quoteExecutable(String executable)
  5. quoteFileName(String filename)
  6. quoteForCommandString(String s)
  7. quoteForCsv(final String field)
  8. quoteForHTML(String toQuote)
  9. quoteForMdx(StringBuilder buf, String val)