打zip后目录结构
--- config
-----------xxxx.properties
--- xxxxxx.jar
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.regex.Matcher;
/**
* @author lidg
* @date 2022/06/27
*/
public enum AppPathUtil {
/**
* 单例实列
*/
INSTANCE,
;
/**
* 打包后相对于项目根路径的资源路径
*/
private static final String RELATIVE_SOURCE_PATH = "config";
private String sourcePath;
private String rootPath;
AppPathUtil() {
init();
}
private void init() {
//获取resource资源路径
File file = new File("");
rootPath = file.getAbsolutePath();
try {
sourcePath = ResourceUtils.getURL("classpath:").getPath();
} catch (FileNotFoundException e) {
//获取不到资源路径,判断系统在服务器上运行
sourcePath = rootPath + File.separator + RELATIVE_SOURCE_PATH;
}
}
/**
* 获取系统根路径
*
* @return
*/
public String getRootPath() {
return rootPath;
}
/**
* 获取resource路径
*
* @return
*/
public String getSourcePath() {
return sourcePath;
}
/**
* 获取应用根路径绝对路径
*
* @param relativePath 相对路径
*
* @return
*/
public String getRootAbsolutPath(String relativePath) {
//将路径分隔符替换为当前系统的路径分隔符
String path = relativePath.replaceAll("[/|\\\\]", Matcher.quoteReplacement(File.separator));
//判断相对路径第一个字符是否有路径分隔符,没有则拼接一个
if ((File.separatorChar != path.trim().charAt(0))) {
return rootPath + File.separator + path;
} else {
return rootPath + path;
}
}
/**
* 获取resource绝对路径
*
* @param relativePath 相对路径
*
* @return 绝对路径
*/
public String getSourceAbsolutPath(String relativePath) {
//将路径分隔符替换为当前系统的路径分隔符
String path = relativePath.replaceAll("[/|\\\\]", Matcher.quoteReplacement(File.separator));
//判断相对路径第一个字符是否有路径分隔符,没有则拼接一个
if ((File.separatorChar == path.trim().charAt(0))) {
return sourcePath + path;
} else {
return sourcePath + File.separator + path;
}
}
/**
* 获取相对路径
*
* @param pathVariable 路径参数列表
* <p>
* 将集合中的路径参数以当前系统的路径分隔符串联起来
* </p>
*
* @return
*/
public String getRelativePath(List<String> pathVariable) {
StringBuilder builder = new StringBuilder();
for (String path : pathVariable) {
if (StringUtils.isNotEmpty(path)) {
//将路径分隔符替换为当前系统的路径分隔符
String rePath = path.replaceAll("[/|\\\\]", Matcher.quoteReplacement(File.separator));
//判断相对路径第一个字符是否有路径分隔符,没有则拼接一个
if ((File.separatorChar != rePath
.trim()
.charAt(0))) {
builder.append(File.separator);
}
builder.append(rePath);
}
}
return builder.toString();
}
/**
* 将指定目录包括子目录下的所有文件路径保存到集合中
*
* @param file 文件夹
* @param pathList 存放文件夹中的文件路径的集合
*
* @throws FileNotFoundException
*/
public void getPathList(File file, List<String> pathList) throws FileNotFoundException {
File[] fs = file.listFiles();
if (fs == null) {
throw new FileNotFoundException("the file not exist");
}
for (File f : fs) {
//若是目录,则递归打印该目录下的文件
if (f.isDirectory()) {
getPathList(f, pathList);
}
//若是文件,直接放入list
if (f.isFile()) {
pathList.add(f.getAbsolutePath());
}
}
}
/**
* 将指定目录包括子目录下的所有文件名保存到集合中
*
* @param file 文件夹
* @param nameList 存放文件夹中文件名的集合
*
* @throws FileNotFoundException
*/
public void getFileNameList(File file, List<String> nameList) throws FileNotFoundException {
File[] fs = file.listFiles();
if (fs == null) {
throw new FileNotFoundException("the file not exist");
}
for (File f : fs) {
//若是目录,则递归打印该目录下的文件
if (f.isDirectory()) {
getPathList(f, nameList);
}
//若是文件,直接放入list
if (f.isFile()) {
nameList.add(f.getName());
}
}
}
}
第二种
能获取某个文件或者文件夹的路径
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache license, Version 2.0
* (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package kl.pki.cacertservice.utils;
import java.io.IOException;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.*;
/**
* <em>Consider this class private.</em> Utility class for ClassLoaders.
*
* @see ClassLoader
* @see RuntimePermission
* @see Thread#getContextClassLoader()
* @see ClassLoader#getSystemClassLoader()
*/
public final class LoaderUtil {
private static final SecurityManager SECURITY_MANAGER = System.getSecurityManager();
private static final boolean GET_CLASS_LOADER_DISABLED;
private static final PrivilegedAction<ClassLoader> TCCL_GETTER = new ThreadContextClassLoaderGetter();
static {
if (SECURITY_MANAGER != null) {
boolean getClassLoaderDisabled;
try {
SECURITY_MANAGER.checkPermission(new RuntimePermission("getClassLoader"));
getClassLoaderDisabled = false;
} catch (final SecurityException ignored) {
getClassLoaderDisabled = true;
}
GET_CLASS_LOADER_DISABLED = getClassLoaderDisabled;
} else {
GET_CLASS_LOADER_DISABLED = false;
}
}
private LoaderUtil() {
}
/**
* Gets the current Thread ClassLoader. Returns the system ClassLoader if the TCCL is {@code null}. If the system
* ClassLoader is {@code null} as well, then the ClassLoader for this class is returned. If running with a
* {@link SecurityManager} that does not allow access to the Thread ClassLoader or system ClassLoader, then the
* ClassLoader for this class is returned.
*
* @return the current ThreadContextClassLoader.
*/
public static ClassLoader getThreadContextClassLoader() {
if (GET_CLASS_LOADER_DISABLED) {
// we can at least get this class's ClassLoader regardless of security context
// however, if this is null, there's really no option left at this point
return LoaderUtil.class.getClassLoader();
}
return SECURITY_MANAGER == null ? TCCL_GETTER.run() : AccessController.doPrivileged(TCCL_GETTER);
}
/**
*
*/
private static class ThreadContextClassLoaderGetter implements PrivilegedAction<ClassLoader> {
@Override
public ClassLoader run() {
final ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl != null) {
return cl;
}
final ClassLoader ccl = LoaderUtil.class.getClassLoader();
return ccl == null && !GET_CLASS_LOADER_DISABLED ? ClassLoader.getSystemClassLoader() : ccl;
}
}
/**
* Finds classpath {@linkplain URL resources}.
*
* @param resource the name of the resource to find.
* @return a Collection of URLs matching the resource name. If no resources could be found, then this will be empty.
* @since 2.1
*/
public static Collection<URL> findResources(final String resource) {
return findResources(resource, true);
}
static Collection<URL> findResources(final String resource, final boolean useTccl) {
final Collection<UrlResource> urlResources = findUrlResources(resource, useTccl);
final Collection<URL> resources = new LinkedHashSet<>(urlResources.size());
for (final UrlResource urlResource : urlResources) {
resources.add(urlResource.getUrl());
}
return resources;
}
static Collection<UrlResource> findUrlResources(final String resource, final boolean useTccl) {
// @formatter:off
final ClassLoader[] candidates = {
useTccl ? getThreadContextClassLoader() : null,
LoaderUtil.class.getClassLoader(),
GET_CLASS_LOADER_DISABLED ? null : ClassLoader.getSystemClassLoader()};
// @formatter:on
final Collection<UrlResource> resources = new LinkedHashSet<>();
Arrays.stream(candidates).forEach(cl->{
if (cl != null) {
try {
final Enumeration<URL> resourceEnum = cl.getResources(resource);
while (resourceEnum.hasMoreElements()) {
resources.add(new UrlResource(cl, resourceEnum.nextElement()));
}
} catch (final IOException e) {
//
throw new RuntimeException("");
}
}
});
for (final ClassLoader cl : candidates) {
if (cl != null) {
try {
final Enumeration<URL> resourceEnum = cl.getResources(resource);
while (resourceEnum.hasMoreElements()) {
resources.add(new UrlResource(cl, resourceEnum.nextElement()));
}
} catch (final IOException e) {
//
}
}
}
return resources;
}
/**
* {@link URL} and {@link ClassLoader} pair.
*/
static class UrlResource {
private final ClassLoader classLoader;
private final URL url;
UrlResource(final ClassLoader classLoader, final URL url) {
this.classLoader = classLoader;
this.url = url;
}
public ClassLoader getClassLoader() {
return classLoader;
}
public URL getUrl() {
return url;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final UrlResource that = (UrlResource) o;
if (classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) {
return false;
}
if (url != null ? !url.equals(that.url) : that.url != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
return Objects.hashCode(classLoader) + Objects.hashCode(url);
}
}
}