集册 Java实例教程 此函数用于获取随机子

此函数用于获取随机子

欢马劈雪     最近更新时间:2020-01-02 10:19:05

348
此函数用于从给定路径获取随机子路径。
/*n o w j a v a . c o m*/


//package com.nowjava;


import java.nio.file.Path;

import java.nio.file.Paths;


public class Main {

    /**

     * 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();

        } 
展开阅读全文