Here you can find the source of getPathRelativeTo(File fileChild, File fileRoot)
Parameter | Description |
---|---|
IllegalArgumentException | if fileChild is null; fileRoot is null; fileChild is not contained under fileRoot |
public static String getPathRelativeTo(File fileChild, File fileRoot) throws IllegalArgumentException
/*/*from w ww .j av a2 s. co m*/ Copyright ? 2008 Brent Boyer This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 Lesser GNU General Public License for more details. You should have received a copy of the Lesser GNU General Public License along with this program (see the license directory in this project). If not, see <http://www.gnu.org/licenses/>. */ import bb.science.FormatUtil; import bb.util.Check; import bb.util.StringUtil; import bb.util.ThrowableUtil; import bb.util.logging.LogUtil; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.util.Random; import java.util.logging.Level; import org.junit.Assert; import org.junit.Test; public class Main{ /** * Returns that portion of the path of fileChild which is relative to the path of fileRoot. * For example, if fileChild.getPath() = "/dirA/dirB/dirC/file1" and fileRoot.getPath() = "/dirA/dirB" * then the result is "dirC/file1". * Note that the result never begins with a path separator char. * Neither File need actually exist; this method simply does String operations on their paths. * If fileChild equals fileRoot, then a blank String is returned. * <p> * @throws IllegalArgumentException if fileChild is null; fileRoot is null; fileChild is not contained under fileRoot */ public static String getPathRelativeTo(File fileChild, File fileRoot) throws IllegalArgumentException { Check.arg().notNull(fileChild); Check.arg().notNull(fileRoot); if (fileChild.equals(fileRoot)) return ""; String pathChild = fileChild.getPath(); String pathRoot = fileRoot.getPath(); if (!pathChild.startsWith(pathRoot)) throw new IllegalArgumentException("fileChild = " + pathChild + " is not contained under fileRoot = " + pathRoot); int skipDirChar = pathRoot.endsWith(File.separator) ? 0 : 1; // handles the directory separator char being present or absent int indexChild = pathRoot.length() + skipDirChar; return pathChild.substring(indexChild); } }