All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.macrocloud.kernel.toolkit.utils.PathUtil Maven / Gradle / Ivy

There is a newer version: 1.1.0-RELEASE
Show newest version
package org.macrocloud.kernel.toolkit.utils;

import org.springframework.lang.Nullable;

import java.io.File;
import java.net.URL;


/**
 * 用来获取各种目录.
 *
 * @author macro
 */
public class PathUtil {
	
	/** The Constant FILE_PROTOCOL. */
	public static final String FILE_PROTOCOL = "file";
	
	/** The Constant JAR_PROTOCOL. */
	public static final String JAR_PROTOCOL = "jar";
	
	/** The Constant ZIP_PROTOCOL. */
	public static final String ZIP_PROTOCOL = "zip";
	
	/** The Constant FILE_PROTOCOL_PREFIX. */
	public static final String FILE_PROTOCOL_PREFIX = "file:";
	
	/** The Constant JAR_FILE_SEPARATOR. */
	public static final String JAR_FILE_SEPARATOR = "!/";

	/**
	 * 获取jar包运行时的当前目录.
	 *
	 * @return {String}
	 */
	@Nullable
	public static String getJarPath() {
		try {
			URL url = PathUtil.class.getResource(StringPool.SLASH).toURI().toURL();
			return PathUtil.toFilePath(url);
		} catch (Exception e) {
			String path = PathUtil.class.getResource(StringPool.EMPTY).getPath();
			return new File(path).getParentFile().getParentFile().getAbsolutePath();
		}
	}

	/**
	 * 转换为文件路径.
	 *
	 * @param url 路径
	 * @return {String}
	 */
	@Nullable
	public static String toFilePath(@Nullable URL url) {
		if (url == null) {
			return null;
		}
		String protocol = url.getProtocol();
		String file = UrlUtil.decode(url.getPath(), Charsets.UTF_8);
		if (FILE_PROTOCOL.equals(protocol)) {
			return new File(file).getParentFile().getParentFile().getAbsolutePath();
		} else if (JAR_PROTOCOL.equals(protocol) || ZIP_PROTOCOL.equals(protocol)) {
			int ipos = file.indexOf(JAR_FILE_SEPARATOR);
			if (ipos > 0) {
				file = file.substring(0, ipos);
			}
			if (file.startsWith(FILE_PROTOCOL_PREFIX)) {
				file = file.substring(FILE_PROTOCOL_PREFIX.length());
			}
			return new File(file).getParentFile().getAbsolutePath();
		}
		return file;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy