Here you can find the source of getRelativePath(final File fromFile, final File toFile)
static String getRelativePath(final File fromFile, final File toFile)
//package com.java2s; /**/* w w w . j a v a 2 s . c o m*/ * Copyright (C) 2010-2012 Andrei Pozolotin <Andrei.Pozolotin@gmail.com> * * All rights reserved. Licensed under the OSI BSD License. * * http://www.opensource.org/licenses/bsd-license.php */ import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Main { static String getRelativePath(final File fromFile, final File toFile) { final String[] fromSegments = getReversePathSegments(fromFile); final String[] toSegments = getReversePathSegments(toFile); String relativePath = ""; int i = fromSegments.length - 1; int j = toSegments.length - 1; // first eliminate common root while ((i >= 0) && (j >= 0) && (fromSegments[i].equals(toSegments[j]))) { i--; j--; } for (; i >= 0; i--) { relativePath += ".." + File.separator; } for (; j >= 1; j--) { relativePath += toSegments[j] + File.separator; } relativePath += toSegments[j]; return relativePath; } static String[] getReversePathSegments(final File file) { final List<String> paths = new ArrayList<String>(); File segment; try { segment = file.getCanonicalFile(); while (segment != null) { paths.add(segment.getName()); segment = segment.getParentFile(); } } catch (final IOException e) { return null; } return paths.toArray(new String[paths.size()]); } }