集册 Java实例教程 获取类路径中包含模式作为子字符串的第一个JAR的完整路径。

获取类路径中包含模式作为子字符串的第一个JAR的完整路径。

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

525
获取类路径中包含模式作为子字符串的第一个JAR的完整路径。

/*

 * Copyright (C) 2006-2007 Mindquarry GmbH, All Rights Reserved

 * 

 * The contents of this file are subject to the Mozilla Public License

 * Version 1.1 (the "License"); you may not use this file except in

 * compliance with the License. You may obtain a copy of the License at

 * http://www.mozilla.org/MPL/

 *

 * Software distributed under the License is distributed on an "AS IS"

 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the

 * License for the specific language governing rights and limitations

 * under the License.

 */

//package com.nowjava;

import java.io.File;
/* 
*来 自
 nowjava - 时  代  Java
*/

import java.io.IOException;

import java.util.HashSet;

import java.util.Set;


public class Main {

    /**

     * Get the full path to the first JAR in classpath that contains 

     * <tt>pattern</tt> as a substring.

     * @throws IOException if pattern cannot be found

     */

    public static String getJar(String pattern) throws IOException {

        Set<String> patterns = new HashSet<String>();

        patterns.add(pattern);

        return getJar(patterns);

    }


    /**

     * Get the full path to the first JAR in classpath that contains 

     * one of <tt>patterns</tt> as a substring.

     * @throws IOException if no pattern can be found

     */

    public static String getJar(Set<String> patterns) throws IOException {

        String path = null;

        String classpath = System.getProperty("java.class.path"); //$NON-NLS-1$/* 来 自 时代Java公众号*/

        String[] cpEntries = classpath.split(File.pathSeparator);

        for (String cpEntry : cpEntries) {

            for (String targetPattern : patterns) {

                if (cpEntry.contains(targetPattern)) {

                    path = cpEntry;

                    break;

                
展开阅读全文