Java Path Relative nio getOptionalPathRelativeToMavenProjectRoot(File absoluteFile)

Here you can find the source of getOptionalPathRelativeToMavenProjectRoot(File absoluteFile)

Description

get Optional Path Relative To Maven Project Root

License

Open Source License

Declaration

static Optional<File> getOptionalPathRelativeToMavenProjectRoot(File absoluteFile) 

Method Source Code


//package com.java2s;
/*// w ww .ja  v  a  2  s  .  c  om
 * Copyright (c) 2016 Red Hat, Inc. and others.  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;
import java.nio.file.Path;
import java.util.Optional;

public class Main {
    static Optional<File> getOptionalPathRelativeToMavenProjectRoot(File absoluteFile) {
        if (!absoluteFile.isAbsolute()) {
            return Optional.of(absoluteFile);
        }
        File projectRoot = absoluteFile;
        while (!isProjectRootDir(projectRoot) && projectRoot.getParentFile() != null) {
            projectRoot = projectRoot.getParentFile();
        }
        if (isProjectRootDir(projectRoot)) {
            Path absolutePath = absoluteFile.toPath();
            Path basePath = projectRoot.toPath();
            Path relativePath = basePath.relativize(absolutePath);
            return Optional.of(relativePath.toFile());
        }
        return Optional.empty();
    }

    private static boolean isProjectRootDir(File file) {
        return new File(file, "pom.xml").exists();
    }
}

Related

  1. combinePaths(String baseDir, String relativePath)
  2. get(File basePath, String... relatives)
  3. getChildEntryRelativePath(Path base, Path child, boolean convertToLinuxPath)
  4. getFileFromBaseFileAndPathThatMayBeRelative(File baseDir, String pathThatMayBeRelative)
  5. getFileRelativeFolders(Path basePath, Path filePath)
  6. getRelativeFilePathToCwd(File file)
  7. getRelativePath(File baseFile, File file, String resultIfImpossible)
  8. getRelativePath(File basePath, File path)
  9. getRelativePath(File root, File f)