Java Relative Path Get relativize(File file, File basedir)

Here you can find the source of relativize(File file, File basedir)

Description

relativize

License

Open Source License

Declaration

public static String relativize(File file, File basedir) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2011 Sonatype, Inc./*from  w  w w.j a  va 2 s.  co  m*/
 * 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
 *******************************************************************************/

import java.io.File;

public class Main {
    public static String relativize(File file, File basedir) {
        if (file == null) {
            return null;
        }
        if (basedir == null) {
            basedir = new File("").getAbsoluteFile();
        } else if (!basedir.isAbsolute()) {
            basedir = basedir.getAbsoluteFile();
        }

        String pathname;

        String basePath = basedir.getPath();
        String filePath = file.getPath();
        if (filePath.startsWith(basePath)) {
            if (filePath.length() == basePath.length()) {
                pathname = "";
            } else if (basePath.endsWith(File.separator)) {
                pathname = filePath.substring(basePath.length());
            } else if (filePath.charAt(basePath.length()) == File.separatorChar) {
                pathname = filePath.substring(basePath.length() + 1);
            } else {
                pathname = null;
            }
        } else {
            pathname = "";
            for (File current = file; !basedir.equals(current);) {
                String filename = current.getName();
                current = current.getParentFile();
                if (current == null) {
                    return null;
                }
                if (pathname.length() > 0) {
                    pathname = filename + File.separatorChar + pathname;
                } else {
                    pathname = filename;
                }
            }
        }

        return pathname;
    }
}

Related

  1. relativePathFiles(String relativePath, final String... fileNamesRegex)
  2. relativeTo(File peer, String filename)
  3. relativeToAbsoluteFilePath(String s)
  4. relativize(File base, File absolute)
  5. relativize(File base, File child)
  6. relativize(File home, File f)
  7. relativize(File path, File relative)
  8. relativize(final File root, final File target)
  9. relativize(String path)