Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.File;
import java.io.IOException;

public class Main {
    public static File getRelativePath(final File file, final File relativeToThis) {
        try {
            return getRelativePath(file.getCanonicalFile(), relativeToThis.getCanonicalFile(), "");
        } catch (final IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static File getRelativePath(final File file, final File relativeToThis, final String relativeInitial) {
        File parent = file;
        String relative = null;
        while (parent != null) {
            if (parent.equals(relativeToThis)) {
                return new File(relativeInitial + (relative == null ? "." : relative));
            }
            relative = parent.getName() + (relative == null ? "" : "/" + relative);
            parent = parent.getParentFile();
        }
        final File toParent = relativeToThis.getParentFile();
        if (toParent == null)
            return null;
        else
            return getRelativePath(file, toParent, "../" + relativeInitial);
    }
}