Return the string representing the parent of the given path - Java File Path IO

Java examples for File Path IO:Path

Description

Return the string representing the parent of the given path

Demo Code


//package com.java2s;

public class Main {
    public static final String SEPARATOR = "/";

    /**//from w w w. ja  v a2 s  .co m
     * 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);
                }
                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 + "+$", "");
        }
        if (path.startsWith(SEPARATOR)) {
            path = path.replaceAll("^" + SEPARATOR + "+", "");
        }
        return path.replaceAll("/+", SEPARATOR);
    }
}

Related Tutorials