Here you can find the source of getRelativePath(File base, File name)
Parameter | Description |
---|---|
base | File that is the base for the result |
name | File to be "relativized" |
public static String getRelativePath(File base, File name)
//package com.java2s; /** This file is part of Approach Avoidance Task. * * Approach Avoidance Task is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version./*from ww w . java 2 s . co m*/ * * Approach Avoidance Task is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Approach Avoidance Task. If not, see <http://www.gnu.org/licenses/>. * */ import java.io.File; public class Main { /** * Computes the path for a file relative to a given base, or fails if the only shared * directory is the root and the absolute form is better. * * @param base File that is the base for the result * @param name File to be "relativized" * @return the relative name */ public static String getRelativePath(File base, File name) { if (base != null && name != null) { File parent = base.getParentFile(); if (name.getName().length() > 0) { try { if (parent == null) { return name.getAbsolutePath(); } String bpath = base.getCanonicalPath(); String fpath = name.getCanonicalPath(); if (fpath.startsWith(bpath)) { return fpath.substring(bpath.length() + 1); } else { return (".." + File.separator + getRelativePath(parent, name)); } } catch (Exception e) { return name.getAbsolutePath(); } } } return ""; } }