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

com.webapp.utils.config.PathUtils Maven / Gradle / Ivy

The newest version!
package com.webapp.utils.config;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class PathUtils {

	private static final Logger logger = LoggerFactory.getLogger(PathUtils.class);

//	public static Path getWebPath(String path) {
//		return Paths.get(encode(getResource("/")).getParent().toString(), path);
//	}
	public static Path getWebPath() {
		return encode(getResource("/")).getParent().getParent();
	}

	public static String getCurPath(Class clz) {
		return encode(clz.getResource("")).toString();
	}

	public static String getClassPath() {
		return encode(getResource("/")).toString();
	}

	public static Path getPath(String path) {
		return encode(getResource(path));
	}

	public static Path getPath(String path, boolean isClasspath) {
		return encode(getResource(path, isClasspath));
	}

	public static boolean isExist(String path) {
		return Files.exists(Paths.get(SysUtils.getUserPath() + path));
	}

	public static URL getResource(String path) {
		return getResource(path, true);
	}

	public static URL getResource(String path, boolean isClasspath) {
		// 根目录
		URL result = null;
		if (isClasspath) {
			result = PathUtils.class.getResource(path);
			if (result == null && !path.contains("/")) {
				result = PathUtils.class.getResource("/" + path);
			}
			return result;
		} else {
			try {
				result = Paths.get(path).toAbsolutePath().toUri().toURL();
			} catch (MalformedURLException e) {
				logger.error("", e);
			}
			return result;
		}

	}

	private static Path encode(URI url) {
		return Paths.get(url);
	}

	private static Path encode(URL url) {
		try {
			return encode(url.toURI());
		} catch (URISyntaxException e) {
			logger.error(PathUtils.class.getSimpleName() + " URL转换URI出错", e);
			throw new RuntimeException(PathUtils.class.getSimpleName()
					+ " URL转换URI出错");
		}
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy