This function is used to get a random sub-path from a given path. - Java File Path IO

Java examples for File Path IO:Path

Description

This function is used to get a random sub-path from a given path.

Demo Code


//package com.java2s;

import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
    /**//w  w w .  j a v  a 2  s.co  m
     * This function is used to get a random sub-path from a given path. The
     * resulted sub-path's depth will be longer than 2.
     * 
     * @param path
     *       is the original path.
     * @return
     *       a random sub-path generated from the given path.
     */
    public static Path getRandomSubpath(Path path) {
        int depth = path.getNameCount();
        int newDepth;
        String newPath;

        if (depth > 2) {
            newDepth = 2 + (int) (Math.random() * 1000000) % (depth - 2);
            newPath = "/" + path.subpath(0, newDepth).toString();
        } else {
            newDepth = depth;
            newPath = path.toString();
        }

        return Paths.get(newPath);
    }
}

Related Tutorials