集册 Java实例教程 等于normalize Path(…),但返回结果路径作为组件,而不是连接它们。

等于normalize Path(…),但返回结果路径作为组件,而不是连接它们。

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

414
等同于标准化Path(...),但返回结果路径作为组件,而不是将它们联接在一起。


//package com.nowjava;
/* from 
n o w j a v a . c o m - 时  代  Java*/

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

import java.util.regex.Pattern;


public class Main {

    /**

     * Split pattern of "/"

     */

    public static final Pattern PATH_SPLIT_PATTERN = Pattern.compile("\\/");

    /**

     * Empty array of strings

     */

    public static final String[] EMPTY_STRINGS = new String[0];


    /**

     * Equal to normalizePath(...) but returns the resultant path as components

     * instead of joining them.

     * @param relativeTo

     * @param path

     * @return list of path components

     */

    public static List<String> normalizePathComponents(String relativeTo,

            String path) {//时代Java公众号 - N o w J a  v a . c o m

        String[] components = splitPath(path);

        ArrayList<String> normalizedComponents = new ArrayList<String>(

                components.length + 10);

        if (!path.startsWith("/")) {

            // It is not absolute.  Append the root components.

            normalizedComponents.addAll(Arrays

                    .asList(splitPath(relativeTo)));

        }


        // Split the path and process each component

        for (String component : components) {

            if (component.isEmpty()) {

                // Just a duplicate slash which happens in sloppy string manipulation.  Ignore

                continue;

            }


            if (".".equals(component)) {

                // Reference to the current component.  Continue

                continue;

            }


            if ("..".equals(component)) {

                // Step up one level

                if (normalizedComponents.isEmpty()) {

                    // Proceeded up past the root

                    return null;

                } else {

                    // Pop the last one

                    normalizedComponents

                            .remove(normalizedComponents.size() - 1);

                    continue;

                }

            }


            // It's just a normal component

            normalizedComponents.add(component);

        }


        return normalizedComponents;

    }


    /**

     * Split the path by sep components (/), ignoring leading and trailing slashes.

     * Append the components to list.

     * @param path

     */

    public static String[] splitPath(String path) {

        path = trimSlashes(path);

        if (path.isEmpty())

            return EMPTY_STRING
展开阅读全文