Java examples for File Path IO:Path
Equal to normalize Path(...) but returns the resultant path as components instead of joining them.
//package com.java2s; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; public class Main { /**//from ww w .ja va 2s. co m * 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) { 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_STRINGS; return PATH_SPLIT_PATTERN.split(path); } /** * Trim leading and trailing slashes from the string, returning the altered string * @param path * @return trimmed path */ public static String trimSlashes(String path) { if (path.startsWith("/")) path = path.substring(1); if (path.endsWith("/")) path = path.substring(0, path.length() - 1); return path; } }