集册 Java实例教程 从组件数组创建路径

从组件数组创建路径

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

517
从组件数组创建路径


import java.io.*;

import java.util.HashMap;

import java.util.Map;
/**
 * 时代Java公众号 - N o w J a  v a . c o m 提 供 
**/

import java.util.regex.Pattern;

import java.util.regex.PatternSyntaxException;


public class Main{

    public static final String SEPARATOR = "/";

    /**

     * create a path from an array of components

     * @param components

     * @return

     */

    public static Path pathFromComponents(String[] components) {

        if (null == components || components.length == 0) {

            return null;

        }/*来 自 时 代 J a v a - N o w J a v a . c o m*/

        return new PathImpl(pathStringFromComponents(components));

    }

    /**

     * create a path from an array of components

     * @param components

     * @return

     */

    public static String pathStringFromComponents(String[] components) {

        if (null == components || components.length == 0) {

            return null;

        }

        return cleanPath(join(components, SEPARATOR));

    }

    /**

     * Clean the path string by removing leading and trailing slashes and removing duplicate slashes.

     * @param path input path

     * @return cleaned path string

     */

    public static String cleanPath(String path) {

        if (path.endsWith(SEPARATOR)) {

            path = path.replaceAll(SEPARATOR + "+$", "");

        }

        if (path.startsWith(SEPARATOR)) {

            path = path.replaceAll("^" + SEPARATOR + "+", "");

        }

        return path.replaceAll("/+", SEPARATOR);

    }

    private 
展开阅读全文