Example usage for org.apache.commons.io FilenameUtils separatorsToWindows

List of usage examples for org.apache.commons.io FilenameUtils separatorsToWindows

Introduction

In this page you can find the example usage for org.apache.commons.io FilenameUtils separatorsToWindows.

Prototype

public static String separatorsToWindows(String path) 

Source Link

Document

Converts all separators to the Windows separator of backslash.

Usage

From source file:jeplus.util.RelativeDirUtil.java

/**
 * Get the relative path from one file to another, specifying the directory separator. If one of the provided resources does not exist,
 * it is assumed to be a file unless it ends with '/' or '\'.
 *
 * @param targetPath targetPath is calculated to this file
 * @param basePath basePath is calculated from this file
 * @param pathSeparator directory separator. The platform default is not assumed so that we can test Unix behaviour when running on
 * Windows (for example)//from  ww  w.j a v  a  2 s.co m
 * @return
 */
public static String getRelativePath(String targetPath, String basePath, String pathSeparator) {

    // Normalize the paths
    String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);
    String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath);
    // Undo the changes to the separators made by normalization
    switch (pathSeparator) {
    case "/":
        normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);
        break;
    case "\\":
        normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath);
        break;
    default:
        throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'");
    }

    String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
    String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));

    // First get all the common elements. Store them as a string,
    // and also count how many of them there are.
    StringBuilder common = new StringBuilder();

    int commonIndex = 0;
    while (commonIndex < target.length && commonIndex < base.length
            && target[commonIndex].equals(base[commonIndex])) {
        common.append(target[commonIndex]).append(pathSeparator);
        commonIndex++;
    }

    if (commonIndex == 0) {
        // No single common path element. This most
        // likely indicates differing drive letters, like C: and D:.
        // These paths cannot be relativized.
        throw new PathResolutionException("No common path element found for '" + normalizedTargetPath
                + "' and '" + normalizedBasePath + "'");
    }

    // The number of directories we have to backtrack depends on whether the base is a file or a dir
    // For example, the relative path from
    //
    // /foo/bar/baz/gg/ff to /foo/bar/baz
    // 
    // ".." if ff is a file
    // "../.." if ff is a directory
    //
    // The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because
    // the resource referred to by this path may not actually exist, but it's the best I can do
    boolean baseIsFile = true;

    File baseResource = new File(normalizedBasePath);

    if (baseResource.exists()) {
        baseIsFile = baseResource.isFile();

    } else if (basePath.endsWith(pathSeparator)) {
        baseIsFile = false;
    }

    StringBuilder relative = new StringBuilder();

    if (base.length != commonIndex) {
        int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;

        for (int i = 0; i < numDirsUp; i++) {
            relative.append("..").append(pathSeparator);
        }
    }
    // deal with current folder (targetPath and basePath are the same)
    if (normalizedTargetPath.length() <= common.length()) {
        relative.append(".");
    } else {
        relative.append(normalizedTargetPath.substring(common.length()));
    }
    return relative.append(pathSeparator).toString();
}

From source file:ddf.catalog.test.AbstractIntegrationTest.java

protected KarafDistributionKitConfigurationOption getPlatformOption(Platform platform) {
    String ddfScript = "bin/ddf";
    String adminScript = "bin/admin";

    if (platform.equals(Platform.WINDOWS)) {
        ddfScript = FilenameUtils.separatorsToWindows(ddfScript) + ".bat";
        adminScript = FilenameUtils.separatorsToWindows(adminScript) + ".bat";
    }/*from www . ja v  a 2s . com*/

    MavenUrlReference ddf = maven().groupId("ddf.distribution").artifactId("ddf").type("zip")
            .versionAsInProject();
    KarafDistributionKitConfigurationOption platformOption = new KarafDistributionKitConfigurationOption(ddf,
            "ddf", KARAF_VERSION, platform).executable(ddfScript).filesToMakeExecutable(adminScript);
    platformOption.unpackDirectory(new File("target/exam"));

    return platformOption;
}

From source file:de.hybris.platform.impex.jalo.ImpExMediasImportTest.java

/**
 * Calls the <code>importData</code> method of given handler with an absolute file path in different formats. Tests
 * path formats in windows and unix notation as well as in relative and absolute.
 * //from   w w w  . jav a 2  s .c o m
 * @param handler
 *           handler which will be used for test
 * @param media
 *           media where the data will be imported to
 */
private void mediaImportFromAbsolute(final MediaDataHandler handler, final Media media) {
    File testFile = null;
    try {
        testFile = File.createTempFile("mediaImportTest", ".txt");
        final PrintWriter printer = new PrintWriter(testFile);
        printer.print("testest");
        printer.close();
    } catch (final IOException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    final String unixPathRel = ImpExConstants.Syntax.ABSOLUTE_FILE_PATH_PREFIX
            + FilenameUtils.separatorsToUnix(testFile.getPath());
    final String unixPathAbs = ImpExConstants.Syntax.ABSOLUTE_FILE_PATH_PREFIX
            + FilenameUtils.separatorsToUnix(testFile.getAbsolutePath());
    final String winPathRel = ImpExConstants.Syntax.ABSOLUTE_FILE_PATH_PREFIX
            + FilenameUtils.separatorsToWindows(testFile.getPath());
    final String winPathAbs = ImpExConstants.Syntax.ABSOLUTE_FILE_PATH_PREFIX
            + FilenameUtils.separatorsToWindows(testFile.getAbsolutePath());

    mediaImport(handler, media, unixPathRel, "testest");
    mediaImport(handler, media, unixPathAbs, "testest");
    mediaImport(handler, media, winPathRel, "testest");
    mediaImport(handler, media, winPathAbs, "testest");
    if (!testFile.delete()) {
        fail("Can not delete temp file: " + testFile.getPath());
    }
}

From source file:fr.fastconnect.factory.tibco.bw.maven.source.AbstractProjectsListMojo.java

/**
 * <p>//w w  w  . j a va2s.  co  m
 * Get the relative path from one file to another, specifying the directory
 * separator. 
 * If one of the provided resources does not exist, it is assumed to be a
 * file unless it ends with '/' or '\'.
 * </p>
 * 
 * @param targetPath targetPath is calculated to this file
 * @param basePath basePath is calculated from this file
 * @param pathSeparator directory separator. The platform default is not assumed so that we can test Unix behaviour when running on Windows (for example)
 * @return
 */
public static String getRelativePath(String targetPath, String basePath, String pathSeparator) {
    // Normalize the paths
    String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);
    String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath);

    // Undo the changes to the separators made by normalization
    if (pathSeparator.equals("/")) {
        normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);

    } else if (pathSeparator.equals("\\")) {
        normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath);

    } else {
        throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'");
    }

    String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
    String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));

    // First get all the common elements. Store them as a string,
    // and also count how many of them there are.
    StringBuffer common = new StringBuffer();

    int commonIndex = 0;
    while (commonIndex < target.length && commonIndex < base.length
            && target[commonIndex].equals(base[commonIndex])) {
        common.append(target[commonIndex] + pathSeparator);
        commonIndex++;
    }

    if (commonIndex == 0) {
        // No single common path element. This most
        // likely indicates differing drive letters, like C: and D:.
        // These paths cannot be relativized.
        throw new PathResolutionException("No common path element found for '" + normalizedTargetPath
                + "' and '" + normalizedBasePath + "'");
    }

    // The number of directories we have to backtrack depends on whether the base is a file or a dir
    // For example, the relative path from
    //
    // /foo/bar/baz/gg/ff to /foo/bar/baz
    // 
    // ".." if ff is a file
    // "../.." if ff is a directory
    //
    // The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because
    // the resource referred to by this path may not actually exist, but it's the best I can do
    boolean baseIsFile = true;

    File baseResource = new File(normalizedBasePath);

    if (baseResource.exists()) {
        baseIsFile = baseResource.isFile();

    } else if (basePath.endsWith(pathSeparator)) {
        baseIsFile = false;
    }

    StringBuffer relative = new StringBuffer();

    if (base.length != commonIndex) {
        int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;

        for (int i = 0; i < numDirsUp; i++) {
            relative.append(".." + pathSeparator);
        }
    }
    relative.append(normalizedTargetPath.substring(common.length()));
    return relative.toString();
}

From source file:de.hybris.platform.impex.jalo.ImpExMediasImportTest.java

/**
 * Calls the <code>importData</code> method of given handler with an zip-file path in different formats.
 * /* w  ww  . j  av a  2 s.  c om*/
 * @param handler
 *           handler which will be used for test
 * @param media
 *           media where the data will be imported to
 */
private void mediaImportFromZip(final MediaDataHandler handler, final Media media) {
    File testFile = null;
    try {
        testFile = File.createTempFile("mediaImportTest", ".zip");
        final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(testFile));
        zos.putNextEntry(new ZipEntry(new File("files", "dummy.txt").getPath()));
        zos.putNextEntry(new ZipEntry(new File("files", "test.txt").getPath()));
        final PrintWriter printer = new PrintWriter(zos);
        printer.print("testest");
        printer.flush();
        zos.flush();
        printer.close();
        zos.close();
    } catch (final IOException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    final String unixPathRel = ImpExConstants.Syntax.ZIP_BASED_FILE_PATH_PREFIX
            + FilenameUtils.separatorsToUnix(testFile.getPath()) + "&files/test.txt";
    final String unixPathAbs = ImpExConstants.Syntax.ZIP_BASED_FILE_PATH_PREFIX
            + FilenameUtils.separatorsToUnix(testFile.getAbsolutePath()) + "&files/test.txt";
    final String winPathRel = ImpExConstants.Syntax.ZIP_BASED_FILE_PATH_PREFIX
            + FilenameUtils.separatorsToWindows(testFile.getPath()) + "&files\\test.txt";
    final String winPathAbs = ImpExConstants.Syntax.ZIP_BASED_FILE_PATH_PREFIX
            + FilenameUtils.separatorsToWindows(testFile.getAbsolutePath()) + "&files\\test.txt";
    try {
        mediaImport(handler, media, unixPathRel, "testest");
        mediaImport(handler, media, unixPathAbs, "testest");
        mediaImport(handler, media, winPathRel, "testest");
        mediaImport(handler, media, winPathAbs, "testest");
    } catch (final Exception e) {
        fail(e.getMessage());
    }
    if (!testFile.delete()) {
        fail("Can not delete temp file: " + testFile.getPath());
    }
}

From source file:endrov.ioImageCollections.EvIONamebasedImageset.java

/**
 * Get the relative path from one file to another, specifying the directory separator. 
 * If one of the provided resources does not exist, it is assumed to be a file unless it ends with '/' or
 * '\'.//from ww  w.  j  a  v a 2  s  .  com
 * 
 * @param targetPath targetPath is calculated to this file
 * @param basePath basePath is calculated from this file
 * @param pathSeparator directory separator. The platform default is not assumed so that we can test Unix behaviour when running on Windows (for example)
 * @return
 */
public static String getRelativePath(String targetPath, String basePath, String pathSeparator) {
    // Normalize the paths
    String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);
    String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath);

    // Undo the changes to the separators made by normalization
    if (pathSeparator.equals("/")) {
        normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);

    } else if (pathSeparator.equals("\\")) {
        normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath);
    } else {
        throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'");
    }

    String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
    String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));

    // First get all the common elements. Store them as a string,
    // and also count how many of them there are.
    StringBuffer common = new StringBuffer();

    int commonIndex = 0;
    while (commonIndex < target.length && commonIndex < base.length
            && target[commonIndex].equals(base[commonIndex])) {
        common.append(target[commonIndex] + pathSeparator);
        commonIndex++;
    }

    if (commonIndex == 0) {
        // No single common path element. This most
        // likely indicates differing drive letters, like C: and D:.
        // These paths cannot be relativized.
        throw new PathResolutionException("No common path element found for '" + normalizedTargetPath
                + "' and '" + normalizedBasePath + "'");
    }

    // The number of directories we have to backtrack depends on whether the
    // base is a file or a dir
    // For example, the relative path from
    //
    // /foo/bar/baz/gg/ff to /foo/bar/baz
    //
    // ".." if ff is a file
    // "../.." if ff is a directory
    //
    // The following is a heuristic to figure out if the base refers to a file
    // or dir. It's not perfect, because
    // the resource referred to by this path may not actually exist, but it's
    // the best I can do
    boolean baseIsFile = true;

    File baseResource = new File(normalizedBasePath);

    if (baseResource.exists()) {
        baseIsFile = baseResource.isFile();

    } else if (basePath.endsWith(pathSeparator)) {
        baseIsFile = false;
    }

    StringBuffer relative = new StringBuffer();

    if (base.length != commonIndex) {
        int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;

        for (int i = 0; i < numDirsUp; i++)
            relative.append(".." + pathSeparator);
    }
    relative.append(normalizedTargetPath.substring(common.length()));
    return relative.toString();
}

From source file:ca.uviccscu.lp.server.main.AddGameDialog.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    Object[] params = new Object[9];
    params[0] = jTextField1.getText();//w w w . j a v  a2s  .  c  om
    params[1] = jTextField2.getText();
    params[2] = jTextField3.getText();
    params[3] = jTextField4.getText();
    params[4] = jTextArea1.getText();
    params[5] = jTextField5.getText();
    params[6] = jTextField6.getText();
    params[7] = jTextField7.getText();
    int verification = GamelistStorage.verifyConfig(params, isEditDialog);
    switch (verification) {
    case (-1): {
        break;
    }
    case (0): {
        JOptionPane.showMessageDialog(this, "Game name incorrect");
        break;
    }
    case (1): {
        JOptionPane.showMessageDialog(this, "Game folder path incorrect");
        break;
    }
    case (2): {
        JOptionPane.showMessageDialog(this, "Game executable path incorrect");
        break;
    }
    case (3): {
        JOptionPane.showMessageDialog(this, "Game flags incorrect");
        break;
    }
    case (4): {
        JOptionPane.showMessageDialog(this, "Bat execution list incorrect");
        break;
    }

    }
    if (verification == -1) {
        game.gameName = jTextField1.getText();
        game.gameAbsoluteFolderPath = jTextField2.getText();
        game.gameAbsoluteExecPath = jTextField3.getText();
        game.gameRuntimeFlags = jTextField4.getText();
        game.gameBatCommands = jTextArea1.getText().split("\\r?\\n");
        String relative = new File(jTextField2.getText()).toURI()
                .relativize(new File(jTextField3.getText()).toURI()).getPath();
        game.gameRelativeExecPath = FilenameUtils.separatorsToWindows(relative);
        game.gamePName = jTextField5.getText();
        game.gamePWName = jTextField6.getText();
        game.gamePUser = jTextField7.getText();
        /*
        String recreated = FilenameUtils.concat(g.gameAbsoluteFolderPath, FilenameUtils.separatorsToWindows(relative));
        File f = new File(recreated);
        l.trace(recreated);
        l.trace(f.exists());
        l.trace(f.getAbsolutePath());
         *
         */
        game.gameStatus = 0;
        l.trace("Game " + game.gameName + " created");
        l.trace("Dir " + game.gameAbsoluteFolderPath);
        Shared.lastCreatedGame = game;
        l.trace(game.toString());
        this.setVisible(false);
        /*
        this.removeAll();
        this.dispose();
         *
         */
    }
}

From source file:net.sf.firemox.xml.magic.Oracle2Xml.java

/**
 * <ul>//from ww w  . j ava  2  s  .com
 * Argument are (in this order :
 * <li>Oracle source file
 * <li>destination directory
 * </ul>
 * 
 * @param args
 */
public static void main(String... args) {
    options = new Options();
    final CmdLineParser parser = new CmdLineParser(options);
    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        // Display help
        if (!options.isHelp()) {
            System.out.println("Wrong parameters : " + e.getMessage());
        } else {
            System.out.println("Usage");
        }
        parser.setUsageWidth(100);
        parser.printUsage(System.out);
        System.exit(-1);
        return;
    }

    if (options.isVersion()) {
        // Display version
        System.out.println("Version is " + IdConst.VERSION);
        System.exit(-1);
        return;
    }

    if (options.isHelp()) {
        // Display help
        System.out.println("Usage");
        parser.setUsageWidth(100);
        parser.printUsage(System.out);
        System.exit(-1);
        return;
    }

    // The oracle source file
    final String oracle = options.getOracleFile();

    // the directory destination end with the file separator
    String destination = FilenameUtils.separatorsToWindows(options.getDestination());
    if (!destination.endsWith("/")) {
        destination += "/";
    }

    // Create the destination directories
    try {
        new File(destination).mkdirs();
    } catch (Exception e) {
        // Ignore this error and continue
    }
    new Oracle2Xml().serialize(MToolKit.getFile(oracle), MToolKit.getFile(destination),
            MToolKit.getFile("tbs/" + TBS_NAME + "/recycled/"));
}

From source file:nl.mvdr.umvc3replayanalyser.controller.FileUtils.java

/**
 * Get the relative path from one file to another, specifying the directory separator. If one of the provided
 * resources does not exist, it is assumed to be a file unless it ends with '/' or '\'.
 * /* w  w  w  .j  a  v a2  s .com*/
 * @param targetPath
 *            targetPath is calculated to this file
 * @param basePath
 *            basePath is calculated from this file
 * @param pathSeparator
 *            directory separator; the platform default is not assumed so that we can test Unix behaviour when
 *            running on Windows (for example)
 * @return relative path
 * @throws PathResolutionException
 *             in case the paths are not related at all
 */
static String getRelativePath(String targetPath, String basePath, String pathSeparator)
        throws PathResolutionException {

    // Normalize the paths
    String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);
    String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath);

    // Undo the changes to the separators made by normalization
    if (pathSeparator.equals("/")) {
        normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);
    } else if (pathSeparator.equals("\\")) {
        normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath);
    } else {
        throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'");
    }

    String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
    String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));

    // First get all the common elements. Store them as a string,
    // and also count how many of them there are.
    StringBuffer common = new StringBuffer();

    int commonIndex = 0;
    while (commonIndex < target.length && commonIndex < base.length
            && target[commonIndex].equals(base[commonIndex])) {
        common.append(target[commonIndex] + pathSeparator);
        commonIndex++;
    }

    if (commonIndex == 0) {
        // No single common path element. This most
        // likely indicates differing drive letters, like C: and D:.
        // These paths cannot be relativized.
        throw new PathResolutionException("No common path element found for '" + normalizedTargetPath
                + "' and '" + normalizedBasePath + "'");
    }

    // The number of directories we have to backtrack depends on whether the base is a file or a dir
    // For example, the relative path from
    //
    // /foo/bar/baz/gg/ff to /foo/bar/baz
    //
    // ".." if ff is a file
    // "../.." if ff is a directory
    //
    // The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because
    // the resource referred to by this path may not actually exist, but it's the best I can do
    boolean baseIsFile = true;

    File baseResource = new File(normalizedBasePath);

    if (baseResource.exists()) {
        baseIsFile = baseResource.isFile();
    } else if (basePath.endsWith(pathSeparator)) {
        baseIsFile = false;
    }

    StringBuffer relative = new StringBuffer();

    if (base.length != commonIndex) {
        int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;

        for (int i = 0; i < numDirsUp; i++) {
            relative.append(".." + pathSeparator);
        }
    }
    relative.append(normalizedTargetPath.substring(common.length()));
    return relative.toString();
}

From source file:org.broad.igv.util.FileUtils.java

/**
 * Get the relative path from one file to another, specifying the directory separator.
 * If one of the provided resources does not exist, it is assumed to be a file unless it ends with '/' or
 * '\'.//from www. j  ava 2s  .  c om
 *
 * @param targetPath    targetPath is calculated to this file
 * @param basePath      basePath is calculated from this file
 * @param pathSeparator directory separator. The platform default is not assumed so that we can test Unix behaviour when running on Windows (for example)
 * @return
 */
public static String getRelativePath(String basePath, String targetPath, String pathSeparator) {

    // Normalize the paths
    String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);
    String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath);

    // Undo the changes to the separators made by normalization
    if (pathSeparator.equals("/")) {
        normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);

    } else if (pathSeparator.equals("\\")) {
        normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath);

    } else {
        throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'");
    }

    String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
    String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));

    // First get all the common elements. Store them as a string,
    // and also count how many of them there are.
    StringBuffer common = new StringBuffer();

    int commonIndex = 0;
    while (commonIndex < target.length && commonIndex < base.length
            && target[commonIndex].equals(base[commonIndex])) {
        common.append(target[commonIndex] + pathSeparator);
        commonIndex++;
    }

    if (commonIndex == 0) {
        // No single common path element. This most
        // likely indicates differing drive letters, like C: and D:.
        // These paths cannot be relativized.
        return targetPath;
    }

    // The number of directories we have to backtrack depends on whether the base is a file or a dir
    // For example, the relative path from
    //
    // /foo/bar/baz/gg/ff to /foo/bar/baz
    //
    // ".." if ff is a file
    // "../.." if ff is a directory
    //
    // The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because
    // the resource referred to by this path may not actually exist, but it's the best I can do
    boolean baseIsFile = true;

    File baseResource = new File(normalizedBasePath);

    if (baseResource.exists()) {
        baseIsFile = baseResource.isFile();

    } else if (basePath.endsWith(pathSeparator)) {
        baseIsFile = false;
    }

    StringBuffer relative = new StringBuffer();

    if (base.length != commonIndex) {
        int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;

        for (int i = 0; i < numDirsUp; i++) {
            relative.append(".." + pathSeparator);
        }
    }
    relative.append(normalizedTargetPath.substring(common.length()));
    return relative.toString();
}