Here you can find the source of getRelativePath(File root, File file)
Parameter | Description |
---|---|
root | the root directory or file |
file | the root contained file or directory |
public static String getRelativePath(File root, File file)
//package com.java2s; /******************************************************************************* * Copyright (c) 2011-2014 Torkild U. Resheim. * * All rights reserved. This program and the accompanying materials are made * available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors:/*from w w w. ja v a2 s .c o m*/ * Torkild U. Resheim - initial API and implementation *******************************************************************************/ import java.io.File; import java.util.ArrayList; public class Main { /** * Determines the <i>root</i> relative path of <i>file</i> in a platform independent manner. The returned string is * a path starting from but excluding <i>root</i> using the '/' character as a directory separator. If the * <i>file</i> argument is a folder a trailing directory separator is added. if the <i>root</i> argument is a file, * it's parent folder will be used. * <p> * Note that if <i>file</i> is <b>not relative</b> to root, it's absolute path will be returned. * </p> * * @param root * the root directory or file * @param file * the root contained file or directory * @return the platform independent, relative path or an absolute path */ public static String getRelativePath(File root, File file) { ArrayList<String> segments = new ArrayList<String>(); if (root.isFile()) { root = root.getParentFile(); } getPathSegments(root, file, segments); StringBuilder path = new StringBuilder(); for (int p = 0; p < segments.size(); p++) { if (p > 0) { path.append('/'); } path.append(segments.get(p)); } if (file.isDirectory()) { path.append('/'); } return path.toString(); } /** * Creates a path segment list. * * @param root * the root folder * @param file * the destination file * @param segments * @see #getRelativePath(File, File) */ private static void getPathSegments(File root, File file, ArrayList<String> segments) { if (root.equals(file) || file == null) { return; } segments.add(0, file.getName()); getPathSegments(root, file.getParentFile(), segments); } }