Java资源文件读取

public static InputStream getResourceAsStream(String resource) {
		String stripped = resource.startsWith("/") ?
				resource.substring(1) : resource;

		InputStream stream = null;
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		if (classLoader!=null) {
			stream = classLoader.getResourceAsStream( stripped );
		}
		if ( stream == null ) {
			stream = Environment.class.getResourceAsStream( resource );
		}
		if ( stream == null ) {
			stream = Environment.class.getClassLoader().getResourceAsStream( stripped );
		}
		if ( stream == null ) {
			throw new HibernateException( resource + " not found" );
		}
		return stream;
	}

 1.首先获取当前线程的ClassLoader读取资源文件(可能和Environment的ClassLoader不是同一个),然后通过相对路径获取资源文件(classpath);

2.如果步骤1未获取成功,这通过class的绝对路径获取资源文件;

3.如果步骤2仍然未获取成功,则通过Environment的ClassLoader的相对路径获取资源文件。

你可能感兴趣的:(java)