PathUtils.java
/*
* Copyright (C) 2021 INRAE AgroClim
*
* This file is part of Indicators.
*
* Indicators is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Indicators is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Indicators. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.inrae.agroclim.indicators.util;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Helper methods for file paths.
*
* Last changed : $Date$
*
* @author $Author$
* @version $Revision$
*/
public abstract class PathUtils {
/**
* The UNIX separator.
*/
private static final String UNIX_SEP = "/";
/**
* Constructs a relative path between a base path and another path.
*
* <p> Relativization is the inverse of {@link #resolve(java.lang.String, java.lang.String) resolution}.
* This method attempts to construct a {@link Path#isAbsolute relative} path that when
* {@link #resolve(java.lang.String, java.lang.String) resolved} against this path, yields a path that locates
* the same file as the given path.</p>
*
* @param basePath absolute path of base directory
* @param absolutePath absolute path to relativize
* @return relative path
*/
public static String relativize(final String basePath, final String absolutePath) {
if (absolutePath == null) {
return null;
}
final Path base = Paths.get(basePath);
final Path absolute = Paths.get(absolutePath);
// example "."
if (base.getRoot() == null) {
return absolutePath;
}
if (UNIX_SEP.equals(base.getRoot().toString())) {
if (!base.getName(0).equals(absolute.getName(0))) {
return absolutePath;
}
} else if (!base.getRoot().equals(absolute.getRoot())) {
return absolutePath;
}
final Path path = base.relativize(absolute);
return path.toString();
}
/**
* Resolve the given path against this path.
*
* <p> Resolution is the inverse of {@link #relativize(java.lang.String, java.lang.String) relativization}.
* If the {@code relativePath} parameter is an {@link Path#isAbsolute() absolute} path then this method trivially
* returns {@code relativePath}.</p>
*
* @param basePath absolute path of base directory
* @param relativePath relative path to resolve
* @return absolute path
*/
public static String resolve(final String basePath, final String relativePath) {
if (relativePath == null) {
return null;
}
if (Paths.get(relativePath).isAbsolute()) {
return relativePath;
}
final Path path = Paths.get(basePath).resolve(relativePath).normalize();
return path.toString();
}
/**
* No constructor for helper class.
*/
private PathUtils() {
//
}
}