Example usage for java.nio.file Path relativize

List of usage examples for java.nio.file Path relativize

Introduction

In this page you can find the example usage for java.nio.file Path relativize.

Prototype

Path relativize(Path other);

Source Link

Document

Constructs a relative path between this path and a given path.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Path p1 = Paths.get("Java_Dev");
    Path p2 = Paths.get("Java_Dev", "recent", "Test");
    System.out.println(p1.relativize(p2));
    System.out.println(p2.relativize(p1));

    Path p3 = Paths.get("Abc");
    Path p4 = Paths.get("Def");
    System.out.println(p3.relativize(p4));
    System.out.println(p4.relativize(p3));
}

From source file:Test.java

public static void main(String[] args) {
    Path firstPath = Paths.get("music/A.mp3");
    Path secondPath = Paths.get("docs");

    System.out.println("From firstPath to secondPath: " + firstPath.relativize(secondPath));
    System.out.println("From secondPath to firstPath: " + secondPath.relativize(firstPath));
    System.out.println();//from w  ww .  j  a va  2 s  .c  o  m

}

From source file:Test.java

public static void main(String[] args) throws Exception {
    Path firstPath = Paths.get("/home/music/users.txt");
    Path secondPath = Paths.get("/docs/status.txt");
    System.out.println("From firstPath to secondPath: " + firstPath.relativize(secondPath));
    System.out.println("From secondPath to firstPath: " + secondPath.relativize(firstPath));
    System.out.println("exists (Do not follow links): " + Files.exists(firstPath, LinkOption.NOFOLLOW_LINKS));
    System.out.println("exists: " + Files.exists(firstPath));
    System.out.println(/*from w  w w  .j  a  va2s  .c o m*/
            "notExists (Do not follow links): " + Files.notExists(firstPath, LinkOption.NOFOLLOW_LINKS));
    System.out.println("notExists: " + Files.notExists(firstPath));

}

From source file:Main.java

public static void main(String[] args) {

    Path path01 = Paths.get("Topic.txt");
    Path path02 = Paths.get("Demo.txt");
    Path path03 = Paths.get("/Java/JavaFX/Topic.txt");
    Path path04 = Paths.get("/Java/2011");

    Path path01_to_path02 = path01.relativize(path02);
    System.out.println(path01_to_path02);

    Path path02_to_path01 = path02.relativize(path01);
    System.out.println(path02_to_path01);

    Path path03_to_path04 = path03.relativize(path04);
    System.out.println(path03_to_path04);

    Path path04_to_path03 = path04.relativize(path03);
    System.out.println(path04_to_path03);
}

From source file:com.github.houbin217jz.thumbnail.Thumbnail.java

public static void main(String[] args) {

    Options options = new Options();
    options.addOption("s", "src", true,
            "????????????");
    options.addOption("d", "dst", true, "");
    options.addOption("r", "ratio", true, "/??, 30%???0.3????????");
    options.addOption("w", "width", true, "(px)");
    options.addOption("h", "height", true, "?(px)");
    options.addOption("R", "recursive", false, "???????");

    HelpFormatter formatter = new HelpFormatter();
    String formatstr = "java -jar thumbnail.jar " + "[-s/--src <path>] " + "[-d/--dst <path>] "
            + "[-r/--ratio double] " + "[-w/--width integer] " + "[-h/--height integer] " + "[-R/--recursive] ";

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;//from  www. j  a  va 2 s.  c  o  m
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e1) {
        formatter.printHelp(formatstr, options);
        return;
    }

    final Path srcDir, dstDir;
    final Integer width, height;
    final Double ratio;

    //
    if (cmd.hasOption("s")) {
        srcDir = Paths.get(cmd.getOptionValue("s")).toAbsolutePath();
    } else {
        srcDir = Paths.get("").toAbsolutePath(); //??
    }

    //
    if (cmd.hasOption("d")) {
        dstDir = Paths.get(cmd.getOptionValue("d")).toAbsolutePath();
    } else {
        formatter.printHelp(formatstr, options);
        return;
    }

    if (!Files.exists(srcDir, LinkOption.NOFOLLOW_LINKS)
            || !Files.isDirectory(srcDir, LinkOption.NOFOLLOW_LINKS)) {
        System.out.println("[" + srcDir.toAbsolutePath() + "]??????");
        return;
    }

    if (Files.exists(dstDir, LinkOption.NOFOLLOW_LINKS)) {
        if (!Files.isDirectory(dstDir, LinkOption.NOFOLLOW_LINKS)) {
            //????????
            System.out.println("????????");
            return;
        }
    } else {
        //????????
        try {
            Files.createDirectories(dstDir);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }

    //??
    if (cmd.hasOption("w") && cmd.hasOption("h")) {
        try {
            width = Integer.valueOf(cmd.getOptionValue("width"));
            height = Integer.valueOf(cmd.getOptionValue("height"));
        } catch (NumberFormatException e) {
            System.out.println("??????");
            return;
        }
    } else {
        width = null;
        height = null;
    }

    //?
    if (cmd.hasOption("r")) {
        try {
            ratio = Double.valueOf(cmd.getOptionValue("r"));
        } catch (NumberFormatException e) {
            System.out.println("?????");
            return;
        }
    } else {
        ratio = null;
    }

    if (width != null && ratio != null) {
        System.out.println("??????????????");
        return;
    }

    if (width == null && ratio == null) {
        System.out.println("????????????");
        return;
    }

    //
    int maxDepth = 1;
    if (cmd.hasOption("R")) {
        maxDepth = Integer.MAX_VALUE;
    }

    try {
        //Java 7 ??@see http://docs.oracle.com/javase/jp/7/api/java/nio/file/Files.html
        Files.walkFileTree(srcDir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), maxDepth,
                new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes)
                            throws IOException {

                        //???&???
                        String filename = path.getFileName().toString().toLowerCase();

                        if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) {
                            //Jpeg??

                            /*
                             * relative??:
                             * rootPath: /a/b/c/d
                             * filePath: /a/b/c/d/e/f.jpg
                             * rootPath.relativize(filePath) = e/f.jpg
                             */

                            /*
                             * resolve??
                             * rootPath: /a/b/c/output
                             * relativePath: e/f.jpg
                             * rootPath.resolve(relativePath) = /a/b/c/output/e/f.jpg
                             */

                            Path dst = dstDir.resolve(srcDir.relativize(path));

                            if (!Files.exists(dst.getParent(), LinkOption.NOFOLLOW_LINKS)) {
                                Files.createDirectories(dst.getParent());
                            }
                            doResize(path.toFile(), dst.toFile(), width, height, ratio);
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.blackducksoftware.integration.hub.detect.workflow.codelocation.FileNameUtils.java

public static String relativize(final String from, final String to) {
    String relative = to;/*w  w w.java  2 s.co  m*/
    try {
        final Path toPath = new File(to).toPath();
        final Path fromPath = new File(from).toPath();
        final Path fromParentPath = fromPath.getParent();
        final Path relativePath = fromParentPath.relativize(toPath);
        final List<String> relativePieces = new ArrayList<>();
        for (int i = 0; i < relativePath.getNameCount(); i++) {
            relativePieces.add(relativePath.getName(i).toFile().getName());
        }
        relative = StringUtils.join(relativePieces, "/");
    } catch (final Exception e) {
        logger.info(String.format("Unable to relativize path, full source path will be used: %s", to));
        logger.debug("The reason relativize failed: ", e);
    }

    return relative;
}

From source file:org.cloudfoundry.util.FileUtils.java

/**
 * Returns a relative and normalized name for a {@link Path}.  This method ensures that directories have a single trailing slash in their name
 *
 * @param root the root {@link Path} to relativize against
 * @param path the {@link Path} to get the name for
 * @return The relative and normalized name
 *//*from   ww  w. java  2s .  c o  m*/
public static String getRelativePathName(Path root, Path path) {
    Path relative = root.relativize(path);
    return Files.isDirectory(path) && !relative.toString().endsWith("/")
            ? String.format("%s/", relative.toString())
            : relative.toString();
}

From source file:com.teradata.tempto.internal.convention.SqlTestsFileUtils.java

private static Consumer<Path> copyFileRecursive(Path source, Path target) {
    return (Path file) -> {
        try {//from   w w  w  .j  a  va2  s .c om
            Files.copy(file, target.resolve(source.relativize(file).toString()), COPY_ATTRIBUTES);
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    };
}

From source file:com.c4om.autoconf.ulysses.configanalyzer.packager.CompressedFileConfigurationPackager.java

/**
 * It takes an absolute {@link File} and returns a {@link File} relative to
 * another given base {@link File}.//  w w w .j  a v a2s  .  c o m
 * 
 * @param absoluteFile the absolute File
 * @param baseFile the base File
 * @return a File relative to baseFile, pointing to the same file than
 *         absoluteFile
 */
protected static File relativizeFile(File absoluteFile, File baseFile) {
    Path absolutePath = absoluteFile.toPath();
    Path basePath = baseFile.toPath();
    Path relativePath = basePath.relativize(absolutePath);
    return relativePath.toFile();
}

From source file:com.kotcrab.vis.editor.util.FileUtils.java

public static String relativize(FileHandle base, FileHandle absolute) {
    Path pathAbsolute = Paths.get(absolute.path());
    Path pathBase = Paths.get(base.path());
    Path pathRelative = pathBase.relativize(pathAbsolute);
    String path = pathRelative.toString().replace("\\", "/");
    if (absolute.isDirectory())
        path += "/";
    return path;/*from   ww w  . ja  v  a 2  s.  co  m*/
}