集册 Java实例教程 返回表示给定路径的父级的字符串

返回表示给定路径的父级的字符串

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

501
返回表示给定路径的父级的字符串


//package com.nowjava;
/*
来 自*
 时 代 J a v a 公 众 号 - N o w J a v  a . c o m
*/


public class Main {

    public static final String SEPARATOR = "/";


    /**

     * Return the string representing the parent of the given path

     * @param path path string

     * @return parent path string

     */

    public static String parentPathString(String path) {

        String[] split = cleanPath(path).split(SEPARATOR);

        if (split.length > 1) {

            StringBuilder stringBuilder = new StringBuilder();

            for (int i = 0; i < split.length - 1; i++) {

                if (i > 0) {

                    stringBuilder.append(SEPARATOR);

                }
                /**来自 
                 nowjava.com - 时代Java**/

                stringBuilder.append(split[i]);

            }

            return stringBuilder.toString();

        }

        return "";

    }


    /**

     * 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 + "+$", "")
展开阅读全文