集册 Java实例教程 用分隔符连接路径段。

用分隔符连接路径段。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

551
用分隔符连接路径段。

/*

 * Copyright 2013 Hewlett-Packard Development Company, L.P

 *

 * Licensed 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.

 */

//package com.nowjava;


public class Main {/* 来自 时 代 J a v a 公 众 号 - nowjava.com*/

    /**

     * Join path segments with separator.

     * <p>

     *

     * If path segment already contains separator on either side of the connecting point it is not duplicated.

     * <p>

     *

     * Examples:

     * pathJoin("/", "a", "b")  ... "a/b"

     * pathJoin("/", "a/", "/b")  ... "a/b"

     * pathJoin("/", "a/", "b/")  ... "a/b/"

     * pathJoin("/")  ... ""

     * pathJoin("/", "a")  ... "a"

     * pathJoin("/", "/a/")  ... "/a/"

     *

     * @param separator segment separator

     * @param parts path segments

     * @return resulting path

     */

    public static String pathJoin(String separator, String... parts) {

        StringBuilder builder = new StringBuilder();

        if (parts.length == 0)

            return "";

        if (parts.length == 1)

            return parts[0];

        for (int i = 0; i < parts.length; i++) {

            String part = parts[i];

            if (i == 0) {

                builder.append(removeEnd(part, separator))

                        .append(separator);

            } else if (i == parts.length - 1) {

                builder.append(removeStart(part, separator));

            } else {

                builder.append(

                        removeStart(removeEnd(part, separator), separator))

                        .append(separator);
                        /* 
                         来自 
                        *nowjava.com - 时  代  Java*/

            }

        }

        return builder.toString();

    }


    public static String removeEnd(String str, String remove) {

        if (str.endsWith(remove)) {

            return str.substring(
展开阅读全文