Thread.currentThread().getContextClassLoader().getResource("")为null
时间: 2023-08-14 12:35:10 浏览: 185
这可能是因为在当前线程的上下文类加载器中找不到资源的原因。可以尝试使用以下代码来获取资源:
```
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource("");
```
这个代码片段中获取的是当前类的类加载器。如果你在其他类中使用这段代码,记得将getClass()替换为你自己的类。另外,如果你需要获取的是某个特定文件的URL,可以在getResource()方法的参数中指定文件名。
相关问题
Thread.currentThread().getContextClassLoader().getResource
This method returns a URL object representing the resource that is located on the classpath. The resource is looked up using the context class loader associated with the current thread. If the resource is not found, null is returned.
Here is an example of how this method can be used:
```
URL resourceUrl = Thread.currentThread().getContextClassLoader().getResource("myResource.txt");
if (resourceUrl != null) {
// Resource found, do something with it
} else {
// Resource not found
}
```
In this example, the method tries to locate a resource named "myResource.txt" on the classpath. If the resource is found, a URL object representing the resource is returned. If the resource is not found, the method returns null. The returned URL can be used to read the contents of the resource or to open a stream to the resource.
static { classpath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); try { classpath = URLDecoder.decode(classpath,"utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // 获取核心配置文件 cfgFile = new File(classpath+"myORM.cfg.xml"); if (cfgFile.exists()){ // 解析配置文件中的数据 Document document = Dom4jUtil.getXmlByPath(cfgFile.getPath()); propConfig = Dom4jUtil.getElementMap(document,"property","name"); mappingSet = Dom4jUtil.getElementSet(document,"mapping","resource"); entitySet = Dom4jUtil.getElementSet(document,"entity","package"); } else { cfgFile = null; System.out.println("未找到核心配置文件myORM.cfg.xml"); } }
这是一个静态代码块,主要用于初始化一些静态变量。首先获取当前线程的类加载器的classpath路径,然后使用UTF-8编码对路径进行解码,接着获取myORM.cfg.xml配置文件的File对象。如果配置文件存在,则使用Dom4jUtil工具类解析配置文件中的数据,包括属性propConfig、映射文件mappingSet和实体类包entitySet;否则将cfgFile置为null,并打印错误信息。
阅读全文