1、路径工具 package com.amiu.util;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.net.URL;import java.util.Properties;public class PathUtil {/** * 获取项目根路径 */public static String getPr
package com.amiu.util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
public class PathUtil {
/**
* 获取项目根路径
*/
public static String getProjectPath() throws IOException {
File directory = new File("");
String projectPath = directory.getCanonicalPath();
return projectPath;
}
/**
* 获取包绝对(编译)路径,packageName为空或空字符串则获取项目(编译)绝对路径
*/
public static String getPackagePath(String packageName) {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
String filePath = "";
if (packageName != null && packageName.length() > 0)
filePath = packageName.replace(".", "/");
URL url = loader.getResource(filePath);
return url.getPath();
}
/**
* 获取类的绝对(编译)路径
*/
public static String getClassPath(Class
clazz) {
String path = "/"+getPackageName(clazz).replace('.', '/');
return clazz.getResource(path).getFile().toString();// .getFile().toString();
}
/**
* 获取当前类所在的包
*/
public static String getPackageName(Class
clazz) {
return clazz.getPackage().getName();
}
// 读取“classpath:”文件,获取输入流
public static InputStream getClasspathInputStream(String fileName)
throws IOException {
if (fileName.startsWith("classpath:"))
fileName = fileName.replaceFirst("classpath:", "").trim();
InputStream is = PathUtil.class.getClassLoader().getResourceAsStream(fileName);
return is;
}
public static void main(String[] args) throws IOException {
//获取项目根路径
System.out.println(PathUtil.getProjectPath());
//获取项目WEB-INF路径
System.out.println(PathUtil.getProjectPath()+"src\\main\\webapp\\WEB-INF");
//获取com包路径(编译路径,我们的.class存放的路径)
System.out.println(PathUtil.getPackagePath("com"));
//获取类PathUtil的编译路径
System.out.println(PathUtil.getClassPath(PathUtil.class));
//获取PathUtil所在包
System.out.println(PathUtil.getPackageName(PathUtil.class));
}
}
2、包扫描
package com.amiu.util;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.junit.Assert;
public class PackageUtil {
/**
* 获取某包下(包括该包的所有子包)所有类
*
* @param packageName
* 包名
* @return 类的完整名称
* @throws IOException
*/
public static List
getClassName(String packageName) throws IOException {
return getClassName(packageName, true);
}
/**
* 以当前运行class下的路径作为基准,获取某包下所有类,可以扫描jar包
* maven src/test/java 文件夹拥有自己的路径 :target\test-classes
* src/main/java 的路径却是 target\classes
* 当我们在src/test/java中运行此方法,获取不到src/main/java中的类
* 这时会导致获取错误路径,获取不到想要的路径,当这个方法出错,推荐使用
* {@link PackageUtil#getClassName(String, boolean)}
*
* @param packageName
* 包名
* @param childPackage
* 是否遍历子包
* @return 类的完整名称
*/
public static List
getCurrentRunClassPathPackageName(String packageName, boolean childPackage) { List
fileNames = null; //以当前运行class的ClassLoader ClassLoader loader = Thread.currentThread().getContextClassLoader(); String packagePath = packageName.replace(".", "/"); URL url = loader.getResource(packagePath); if (url != null) { String type = url.getProtocol(); if (type.equals("file")) { fileNames = getClassNameByFile(url.getPath(), null, childPackage); } else if (type.equals("jar")) { fileNames = getClassNameByJar(url.getPath(), childPackage); } } else { fileNames = getClassNameByJars(((URLClassLoader) loader).getURLs(), packagePath, childPackage); } return fileNames; } /** * 获取某包下所有类 * @param packageName 包名 * @param childPackage 是否遍历子包 * @return 类的完整名称 * @throws IOException */ public static List
getClassName(String packageName, boolean childPackage) throws IOException { List
fileNames = null; ClassLoader loader = Thread.currentThread().getContextClassLoader(); String packagePath = packageName.replace(".", "/"); //获取所有资源,这里能获取到maven的/target/test-classes 和 /target/classes/ Enumeration
dirs = loader.getResources(packagePath); while (dirs.hasMoreElements()) { URL url = dirs.nextElement(); if (url != null) { String type = url.getProtocol(); if (type.equals("file")) { fileNames = getClassNameByFile(url.getPath(), null, childPackage); } else if (type.equals("jar")) { fileNames = getClassNameByJar(url.getPath(), childPackage); } } else { fileNames = getClassNameByJars(((URLClassLoader) loader).getURLs(), packagePath, childPackage); } } return fileNames; } /** * 从项目文件获取某包下所有类 * * @param filePath * 文件路径 * @param className * 类名集合 * @param childPackage * 是否遍历子包 * @return 类的完整名称 */ private static List
getClassNameByFile(String filePath, List
className, boolean childPackage) { List
myClassName = new ArrayList
(); File file = new File(filePath); File[] childFiles = file.listFiles(); for (File childFile : childFiles) { if (childFile.isDirectory()) { if (childPackage) { myClassName.addAll(getClassNameByFile(childFile.getPath(), myClassName, childPackage)); } } else { String childFilePath = childFile.getPath(); if (childFilePath.endsWith(".class")) { childFilePath = childFilePath.substring( childFilePath.indexOf("\\classes") + 9, childFilePath.lastIndexOf(".")); childFilePath = childFilePath.replace("\\", "."); myClassName.add(childFilePath); } } } return myClassName; } /** * 从jar获取某包下所有类 * * @param jarPath * jar文件路径 * @param childPackage * 是否遍历子包 * @return 类的完整名称 */ private static List
getClassNameByJar(String jarPath, boolean childPackage) { List
myClassName = new ArrayList
(); String[] jarInfo = jarPath.split("!"); String jarFilePath = jarInfo[0].substring(jarInfo[0].indexOf("/")); String packagePath = jarInfo[1].substring(1); try { JarFile jarFile = new JarFile(jarFilePath); Enumeration
entrys = jarFile.entries(); while (entrys.hasMoreElements()) { JarEntry jarEntry = entrys.nextElement(); String entryName = jarEntry.getName(); if (entryName.endsWith(".class")) { if (childPackage) { if (entryName.startsWith(packagePath)) { entryName = entryName.replace("/", ".").substring( 0, entryName.lastIndexOf(".")); myClassName.add(entryName); } } else { int index = entryName.lastIndexOf("/"); String myPackagePath; if (index != -1) { myPackagePath = entryName.substring(0, index); } else { myPackagePath = entryName; } if (myPackagePath.equals(packagePath)) { entryName = entryName.replace("/", ".").substring( 0, entryName.lastIndexOf(".")); myClassName.add(entryName); } } } } } catch (Exception e) { e.printStackTrace(); } return myClassName; } /** * 从所有jar中搜索该包,并获取该包下所有类 * * @param urls * URL集合 * @param packagePath * 包路径 * @param childPackage * 是否遍历子包 * @return 类的完整名称 */ private static List
getClassNameByJars(URL[] urls, String packagePath, boolean childPackage) { List
myClassName = new ArrayList
(); if (urls != null) { for (int i = 0; i < urls.length; i++) { URL url = urls[i]; String urlPath = url.getPath(); // 不必搜索classes文件夹 if (urlPath.endsWith("classes/")) { continue; } String jarPath = urlPath + "!/" + packagePath; myClassName.addAll(getClassNameByJar(jarPath, childPackage)); } } return myClassName; } }
