Java中,关于资源Resource的定位问题

2024-08-30 00:32

本文主要是介绍Java中,关于资源Resource的定位问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

通过class的getResource方法,查找与给定类相关的资源

1、class中getResource在JDK中的定义


URL java. lang. Class.getResource( String name)

Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the definingclass loader of the class. This method delegates to this object's class loader. If this object was loaded by the bootstrap class loader, the method delegates toClassLoader.getSystemResource.

Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

  • If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of thename following the '/'.
  • Otherwise, the absolute name is of the following form:
       modified_package_name/name

    Where the modified_package_name is the package name of this object with'/' substituted for '.' ('\u002e').

Parameters:
name name of the desired resource
Returns:
A java.net.URL object or null if no resource with this name is found
Since:
JDK1.1

getResource

public URL getResource(String name)
查找带有给定名称的资源。查找与给定类相关的资源的规则是通过定义类的 class loader 实现的。此方法委托给此对象的类加载器。如果此对象通过引导类加载器加载,则此方法将委托给 ClassLoader.getSystemResource(java.lang.String)

在委托前,使用下面的算法从给定的资源名构造一个绝对资源名:

  • 如果 name'/' ('\u002f') 开始,则绝对资源名是 '/' 后面的name 的一部分。
  • 否则,绝对名具有以下形式:
       modified_package_name/name
    

    其中 modified_package_name 是此对象的包名,该名用 '/' 取代了 '.' ('\u002e')。


参数:
name - 所需资源的名称
返回:
一个 URL 对象;如果找不到带有该名称的资源,则返回 null
从以下版本开始:
JDK1.1

getResource方法的实现如下

//getResourcepublic java.net.URL getResource(String name) {name = resolveName(name);ClassLoader cl = getClassLoader0();if (cl==null) {// A system class.return ClassLoader.getSystemResource(name);}return cl.getResource(name);}//resolveNameprivate String resolveName(String name) {if (name == null) {return name;}if (!name.startsWith("/")) {Class c = this;while (c.isArray()) {c = c.getComponentType();}String baseName = c.getName();int index = baseName.lastIndexOf('.');if (index != -1) {name = baseName.substring(0, index).replace('.', '/')+"/"+name;}} else {name = name.substring(1);}return name;}


2、classloader中的getResource在JDK中的定义

URL java. lang. ClassLoader.getResource( String name)

Finds the resource with the given name. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code.

The name of a resource is a '/'-separated path name that identifies the resource.

This method will first search the parent class loader for the resource; if the parent isnull the path of the class loader built-in to the virtual machine is searched. That failing, this method will invokefindResource(String) to find the resource.

Parameters:
name The resource name
Returns:
A URL object for reading the resource, or null if the resource could not be found or the invoker doesn't have adequate privileges to get the resource.
Since:
1.1

getResource

public URL getResource(String name)
查找具有给定名称的资源。资源是可以通过类代码以与代码基无关的方式访问的一些数据(图像、声音、文本等)。

资源名称是以 '/' 分隔的标识资源的路径名称。

此方法首先搜索资源的父类加载器;如果父类加载器为 null,则搜索的路径就是虚拟机的内置类加载器的路径。如果搜索失败,则此方法将调用 findResource(String) 来查找资源。

参数:
name - 资源名称
返回:
读取资源的 URL 对象;如果找不到该资源,或者调用者没有足够的权限获取该资源,则返回 null
从以下版本开始:
1.1

getResource方法的实现如下

    //getResourcepublic URL getResource(String name) {URL url;if (parent != null) {url = parent.getResource(name);} else {url = getBootstrapResource(name);}if (url == null) {url = findResource(name);}return url;}/*** Find resources from the VM's built-in classloader.*/private static URL getBootstrapResource(String name) {try {// If this is a known JRE resource, ensure that its bundle is // downloaded.  If it isn't known, we just ignore the download// failure and check to see if we can find the resource anyway// (which is possible if the boot class path has been modified).sun.jkernel.DownloadManager.getBootClassPathEntryForResource(name);} catch (NoClassDefFoundError e) {// This happens while Java itself is being compiled; DownloadManager// isn't accessible when this code is first invoked.  It isn't an// issue, as if we can't find DownloadManager, we can safely assume// that additional code is not available for download.}URLClassPath ucp = getBootstrapClassPath();Resource res = ucp.getResource(name);return res != null ? res.getURL() : null;}/*** Finds the resource with the given name. Class loader implementations* should override this method to specify where to find resources.  </p>** @param  name*         The resource name** @return  A <tt>URL</tt> object for reading the resource, or*          <tt>null</tt> if the resource could not be found** @since  1.2*/protected URL findResource(String name) {return null;}



 

3、总结

获取资源是,推荐使用class的getResource方法,它实质上是调用的classloader的getResource方法。

class的getResource方法,对name的路径做了一下解析,

所以,自己没有必要调用classloader的getResource方法(因为它的参数name是有规则要求的,但是在API中没有体现。从类路径下搜索,不能以"/"开头)。

例如:

package org.wsr.spring.demo;public class Demo {public static void main(String[] args) throws Exception {String path = new Demo().getClass().getClassLoader().getResource("").getPath();System.out.println(path);path = new Demo().getClass().getResource("").getPath();System.out.println(path);path = Demo.class.getResource("text.txt").getPath();System.out.println(path);}
}//  output
// /D:/WorkSpace/e_my_work/beantest/target/classes/
// /D:/WorkSpace/e_my_work/beantest/target/classes/org/wsr/spring/demo/
// /D:/WorkSpace/e_my_work/beantest/target/classes/org/wsr/spring/demo/text.txt





这篇关于Java中,关于资源Resource的定位问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1119290

相关文章

Java中Switch Case多个条件处理方法举例

《Java中SwitchCase多个条件处理方法举例》Java中switch语句用于根据变量值执行不同代码块,适用于多个条件的处理,:本文主要介绍Java中SwitchCase多个条件处理的相... 目录前言基本语法处理多个条件示例1:合并相同代码的多个case示例2:通过字符串合并多个case进阶用法使用

Java中的Lambda表达式及其应用小结

《Java中的Lambda表达式及其应用小结》Java中的Lambda表达式是一项极具创新性的特性,它使得Java代码更加简洁和高效,尤其是在集合操作和并行处理方面,:本文主要介绍Java中的La... 目录前言1. 什么是Lambda表达式?2. Lambda表达式的基本语法例子1:最简单的Lambda表

Java中Scanner的用法示例小结

《Java中Scanner的用法示例小结》有时候我们在编写代码的时候可能会使用输入和输出,那Java也有自己的输入和输出,今天我们来探究一下,对JavaScanner用法相关知识感兴趣的朋友一起看看吧... 目录前言一 输出二 输入Scanner的使用多组输入三 综合练习:猜数字游戏猜数字前言有时候我们在

Spring Security+JWT如何实现前后端分离权限控制

《SpringSecurity+JWT如何实现前后端分离权限控制》本篇将手把手教你用SpringSecurity+JWT搭建一套完整的登录认证与权限控制体系,具有很好的参考价值,希望对大家... 目录Spring Security+JWT实现前后端分离权限控制实战一、为什么要用 JWT?二、JWT 基本结构

java解析jwt中的payload的用法

《java解析jwt中的payload的用法》:本文主要介绍java解析jwt中的payload的用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java解析jwt中的payload1. 使用 jjwt 库步骤 1:添加依赖步骤 2:解析 JWT2. 使用 N

springboot项目如何开启https服务

《springboot项目如何开启https服务》:本文主要介绍springboot项目如何开启https服务方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录springboot项目开启https服务1. 生成SSL证书密钥库使用keytool生成自签名证书将

Java实现优雅日期处理的方案详解

《Java实现优雅日期处理的方案详解》在我们的日常工作中,需要经常处理各种格式,各种类似的的日期或者时间,下面我们就来看看如何使用java处理这样的日期问题吧,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言一、日期的坑1.1 日期格式化陷阱1.2 时区转换二、优雅方案的进阶之路2.1 线程安全重构2

Java中的JSONObject详解

《Java中的JSONObject详解》:本文主要介绍Java中的JSONObject详解,需要的朋友可以参考下... Java中的jsONObject详解一、引言在Java开发中,处理JSON数据是一种常见的需求。JSONObject是处理JSON对象的一个非常有用的类,它提供了一系列的API来操作J

SpringBoot多数据源配置完整指南

《SpringBoot多数据源配置完整指南》在复杂的企业应用中,经常需要连接多个数据库,SpringBoot提供了灵活的多数据源配置方式,以下是详细的实现方案,需要的朋友可以参考下... 目录一、基础多数据源配置1. 添加依赖2. 配置多个数据源3. 配置数据源Bean二、JPA多数据源配置1. 配置主数据

将Java程序打包成EXE文件的实现方式

《将Java程序打包成EXE文件的实现方式》:本文主要介绍将Java程序打包成EXE文件的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录如何将Java程序编程打包成EXE文件1.准备Java程序2.生成JAR包3.选择并安装打包工具4.配置Launch4