package cn.com.qmth.examcloud.commons.util; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLDecoder; /** * 路径工具 * * @author WANGWEI */ public class PathUtil { /** * 获取标准路径 * * @author WANGWEI * @param path * @return */ public static String getCanonicalPath(String path) { path = path.replaceAll("\\\\+", "/"); path = path.replaceAll("/+", "/"); return path; } /** * 以"/"开头 * * @author WANGWEI * @param path * @return */ public static String startsWithSeparator(String path) { path = getCanonicalPath(path); if (path.startsWith("/")) { return path; } return "/" + path; } /** * 不以"/"开头 * * @author WANGWEI * @param path * @return */ public static String startsWithoutSeparator(String path) { path = getCanonicalPath(path); if (path.startsWith("/")) { return path.substring(1); } return path; } /** * 以"/"结尾 * * @author WANGWEI * @param path * @return */ public static String endsWithSeparator(String path) { path = getCanonicalPath(path); if (path.endsWith("/")) { return path; } return path + "/"; } /** * 不以"/"结尾 * * @author WANGWEI * @param path * @return */ public static String endsWithoutSeparator(String path) { path = getCanonicalPath(path); if (path.endsWith("/")) { return path.substring(0, path.length() - 1); } return path; } /** * 获取路径 * * @author WANGWEI * @param file * @return */ public static String getCanonicalPath(File file) { try { return file.getCanonicalPath(); } catch (IOException e) { throw new RuntimeException("Fail to get canonical path.", e); } } /** * 获取当前路径 * * @author WANGWEI * @return * @throws IOException */ public static String currentPath() { File directory = new File(". "); return getCanonicalPath(directory); } /** * 获取资源路径 * * @author WANGWEI * @param resourceName * @return */ public static String getResoucePath(String resourceName) { try { ClassLoader classLoader = PathUtil.class.getClassLoader(); URL url = classLoader.getResource(resourceName); if (null != url) { String path = URLDecoder.decode(url.getPath(), "UTF-8"); return path; } else { return null; } } catch (Exception e) { throw new RuntimeException(e); } } /** * 获取windows盘符 * * @author WANGWEI * @param path * @return */ public static String getDrive(String path) { if (path.matches("[a-zA-Z]:[\\\\/].*")) { return path.substring(0, 2); } else { throw new RuntimeException("Path is not a windows path."); } } /** * 拼接路径 * * @author WANGWEI * @param fragments * @return */ public static String joinUrl(String... fragments) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < fragments.length; i++) { String cur = fragments[i].trim(); if (cur.endsWith("/")) { cur = cur.substring(0, cur.length() - 1); } if (0 == i) { sb.append(cur); } else if (cur.startsWith("/")) { sb.append(cur); } else { sb.append("/").append(cur); } } return sb.toString(); } }