Here you can find the source of getRelativePath(File basePath, File path)
Parameter | Description |
---|---|
basePath | a parameter |
path | a parameter |
public static String getRelativePath(File basePath, File path)
//package com.java2s; /*/*w w w . ja v a 2 s. c om*/ * Copyright 2011 gitblit.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; public class Main { /** * Determine the relative path between two files. Takes into account * canonical paths, if possible. * * @param basePath * @param path * @return a relative path from basePath to path */ public static String getRelativePath(File basePath, File path) { Path exactBase = Paths.get(getExactFile(basePath).toURI()); Path exactPath = Paths.get(getExactFile(path).toURI()); if (exactPath.startsWith(exactBase)) { return exactBase.relativize(exactPath).toString() .replace('\\', '/'); } // no relative relationship return null; } /** * Returns the exact path for a file. This path will be the canonical path * unless an exception is thrown in which case it will be the absolute path. * * @param path * @return the exact file */ public static File getExactFile(File path) { try { return path.getCanonicalFile(); } catch (IOException e) { return path.getAbsoluteFile(); } } }