springboot中关于classpath:路径使用及说明

2022-11-13 17:11:13 classpath 路径 springboot

1. 案例说明

在 resources下有model.conf文件,在配置文件中使用classpath:做为文件路径

1.1 解决方案

1.1.1 使用ResourcePatternResolver实现

使用classpath:做为路径

通过@value获取配置文件中的路径,后经过ResourcePatternResolver 获取文件

ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource resource = resolver.getResource("classpath:model.conf");
        String path = resource.getFile().getCanonicalPath();

1.1.2 使用 ClassPathResource实现

 ClassPathResource resource = new ClassPathResource("model.conf");
        String path = resource.getFile().getCanonicalPath();

ClassPathResource使用时,文件路径中不存在classpath:

1.1.3 使用Spring框架中ResourceUtils实现

File file = ResourceUtils.getFile("classpath:model.conf");
String path = file.getCanonicalPath();

2. ResourceUtils使用说明

2.1 源码展示


public abstract class ResourceUtils {
	
	public static final String CLASSPATH_URL_PREFIX = "classpath:";
	
	public static final String FILE_URL_PREFIX = "file:";
	
	public static final String JAR_URL_PREFIX = "jar:";
	
	public static final String WAR_URL_PREFIX = "war:";
	
	public static final String URL_PROTOCOL_FILE = "file";
	
	public static final String URL_PROTOCOL_JAR = "jar";
	
	public static final String URL_PROTOCOL_WAR = "war";
	
	public static final String URL_PROTOCOL_ZIP = "zip";
	
	public static final String URL_PROTOCOL_WSJAR = "wsjar";
	
	public static final String URL_PROTOCOL_VFSZIP = "vfszip";
	
	public static final String URL_PROTOCOL_VFSFILE = "vfsfile";
	
	public static final String URL_PROTOCOL_VFS = "vfs";
	
	public static final String JAR_FILE_EXTENSioN = ".jar";
	
	public static final String JAR_URL_SEPARATOR = "!/";
	
	public static final String WAR_URL_SEPARATOR = "*/";
	
	public static boolean isUrl(@Nullable String resourceLocation) {
		if (resourceLocation == null) {
			return false;
		}
		if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
			return true;
		}
		try {
			new URL(resourceLocation);
			return true;
		}
		catch (MalfORMedURLException ex) {
			return false;
		}
	}
	
	public static URL getURL(String resourceLocation) throws FileNotFoundException {
		Assert.notNull(resourceLocation, "Resource location must not be null");
		if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
			String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length());
			ClassLoader cl = ClassUtils.getDefaultClassLoader();
			URL url = (cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path));
			if (url == null) {
				String description = "class path resource [" + path + "]";
				throw new FileNotFoundException(description +
						" cannot be resolved to URL because it does not exist");
			}
			return url;
		}
		try {
			// try URL
			return new URL(resourceLocation);
		}
		catch (MalformedURLException ex) {
			// no URL -> treat as file path
			try {
				return new File(resourceLocation).toURI().toURL();
			}
			catch (MalformedURLException ex2) {
				throw new FileNotFoundException("Resource location [" + resourceLocation +
						"] is neither a URL not a well-formed file path");
			}
		}
	}
	
	public static File getFile(String resourceLocation) throws FileNotFoundException {
		Assert.notNull(resourceLocation, "Resource location must not be null");
		if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
			String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length());
			String description = "class path resource [" + path + "]";
			ClassLoader cl = ClassUtils.getDefaultClassLoader();
			URL url = (cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path));
			if (url == null) {
				throw new FileNotFoundException(description +
						" cannot be resolved to absolute file path because it does not exist");
			}
			return getFile(url, description);
		}
		try {
			// try URL
			return getFile(new URL(resourceLocation));
		}
		catch (MalformedURLException ex) {
			// no URL -> treat as file path
			return new File(resourceLocation);
		}
	}
	
	public static File getFile(URL resourceUrl) throws FileNotFoundException {
		return getFile(resourceUrl, "URL");
	}
	
	public static File getFile(URL resourceUrl, String description) throws FileNotFoundException {
		Assert.notNull(resourceUrl, "Resource URL must not be null");
		if (!URL_PROTOCOL_FILE.equals(resourceUrl.getProtocol())) {
			throw new FileNotFoundException(
					description + " cannot be resolved to absolute file path " +
					"because it does not reside in the file system: " + resourceUrl);
		}
		try {
			return new File(toURI(resourceUrl).getSchemeSpecificPart());
		}
		catch (URISyntaxException ex) {
			// Fallback for URLs that are not valid URIs (should hardly ever happen).
			return new File(resourceUrl.getFile());
		}
	}
	
	public static File getFile(URI resourceUri) throws FileNotFoundException {
		return getFile(resourceUri, "URI");
	}
	
	public static File getFile(URI resourceUri, String description) throws FileNotFoundException {
		Assert.notNull(resourceUri, "Resource URI must not be null");
		if (!URL_PROTOCOL_FILE.equals(resourceUri.getScheme())) {
			throw new FileNotFoundException(
					description + " cannot be resolved to absolute file path " +
					"because it does not reside in the file system: " + resourceUri);
		}
		return new File(resourceUri.getSchemeSpecificPart());
	}
	
	public static boolean isFileURL(URL url) {
		String protocol = url.getProtocol();
		return (URL_PROTOCOL_FILE.equals(protocol) || URL_PROTOCOL_VFSFILE.equals(protocol) ||
				URL_PROTOCOL_VFS.equals(protocol));
	}
	
	public static boolean isJarURL(URL url) {
		String protocol = url.getProtocol();
		return (URL_PROTOCOL_JAR.equals(protocol) || URL_PROTOCOL_WAR.equals(protocol) ||
				URL_PROTOCOL_ZIP.equals(protocol) || URL_PROTOCOL_VFSZIP.equals(protocol) ||
				URL_PROTOCOL_WSJAR.equals(protocol));
	}
	
	public static boolean isJarFileURL(URL url) {
		return (URL_PROTOCOL_FILE.equals(url.getProtocol()) &&
				url.getPath().toLowerCase().endsWith(JAR_FILE_EXTENSION));
	}
	
	public static URL extractJarFileURL(URL jarUrl) throws MalformedURLException {
		String urlFile = jarUrl.getFile();
		int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR);
		if (separatorIndex != -1) {
			String jarFile = urlFile.substring(0, separatorIndex);
			try {
				return new URL(jarFile);
			}
			catch (MalformedURLException ex) {
				// Probably no protocol in original jar URL, like "jar:C:/mypath/myjar.jar".
				// This usually indicates that the jar file resides in the file system.
				if (!jarFile.startsWith("/")) {
					jarFile = "/" + jarFile;
				}
				return new URL(FILE_URL_PREFIX + jarFile);
			}
		}
		else {
			return jarUrl;
		}
	}
	
	public static URL extractArcHiveURL(URL jarUrl) throws MalformedURLException {
		String urlFile = jarUrl.getFile();
		int endIndex = urlFile.indexOf(WAR_URL_SEPARATOR);
		if (endIndex != -1) {
			// Tomcat's "war:file:...mywar.war*/WEB-INF/lib/myjar.jar!/myentry.txt"
			String warFile = urlFile.substring(0, endIndex);
			if (URL_PROTOCOL_WAR.equals(jarUrl.getProtocol())) {
				return new URL(warFile);
			}
			int startIndex = warFile.indexOf(WAR_URL_PREFIX);
			if (startIndex != -1) {
				return new URL(warFile.substring(startIndex + WAR_URL_PREFIX.length()));
			}
		}
		// Regular "jar:file:...myjar.jar!/myentry.txt"
		return extractJarFileURL(jarUrl);
	}
	
	public static URI toURI(URL url) throws URISyntaxException {
		return toURI(url.toString());
	}
	
	public static URI toURI(String location) throws URISyntaxException {
		return new URI(StringUtils.replace(location, " ", "%20"));
	}
	
	public static void useCachesIfNecessary(URLConnection con) {
		con.setUseCaches(con.getClass().getSimpleName().startsWith("JNLP"));
	}
}

2.2 常用方法

2.2.1 extractJarFileURL

public static URL extractJarFileURL(URL jarUrl)

从给定的URL (URL可以指向jar文件中的资源或jar文件本身)中提取实际jar文件的URL

2.2.2 getFile

  • getFile(String resourceLocation):将给定的资源位置解析为java.io.file
  • getFile(URI resourceUri) :将给定的资源位置解析为java.io.file
  • getFile(String resourceLocation) :将给定的资源位置解析为java.io.file
  • getFile(URL resourceUrl, String description) :将给定的资源位置解析为java.io.file
  • getFile(URL resourceUrl, String description) :将给定的资源位置解析为java.io.file

2.2.3 getURL

getURL(String resourceLocation)

将给定的资源位置解析为java.net.URL

2.2.4 isJarURL

isJarURL(URL url)

确定给定的URL是否指向jar文件中的资源,即具有协议“jar”、“zip”、“wsjar”或“代码源”

2.2.5 isUrl

返回给定资源位置是否是URL:一个特殊的“classpath”伪URL还是一个标准URL。

2.2.6 toURI

  • toURI(String location) :为给定的URL创建一个URI实例,首先用“%20”引号替换空格。
  • toURI(URL url) :为给定的URL创建一个URI实例,首先用“%20”引号替换空格。

3. 常见问题

3.1 打成jar后获取不到文件

Resource下的文件是存在于jar这个文件里面,在磁盘上是没有真实路径存在的,它是位于jar内部的一个路径。所以通过ResourceUtils.getFile或者this.getClass().getResource("")方法无法正确获取文件。

解决方案:

BufferedReader in = new BufferedReader(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(path)));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null){
    buffer.append(line);
}
String input = buffer.toString();

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

相关文章