根据ClassLoader获取资源文件

    private void display() {
        String path=this.getClass().getResource("").getPath();
        System.out.println(path);
        path=this.getClass().getResource("/loadresource").getPath();
        System.out.println(path);
        path=this.getClass().getResource("/loadresource/bp.txt").getPath();
        System.out.println(path);
        path=this.getClass().getResource("/").getPath();
        System.out.println(path);
        URL url=this.getClass().getResource("loadresource/bp.txt");
        System.out.println("Is Null:"+(url==null));

        path=GetResouceTest.class.getClassLoader().getResource("").getPath();
        System.out.println(path);
        path=GetResouceTest.class.getClassLoader().getResource("loadresource/bp.txt").getPath();
        System.out.println(path);
        url=GetResouceTest.class.getClassLoader().getResource("/loadresource/bp.txt");
        System.out.println("Is Null:"+(url==null));
    }

Output:

/E:/java/workspace/test/bin/loadresource/
/E:/java/workspace/test/bin/loadresource
/E:/java/workspace/test/bin/loadresource/bp.txt
/E:/java/workspace/test/bin/
Is Null:true
/E:/java/workspace/test/bin//E:/java/workspace/test/bin/loadresource/bp.txt
Is Null:true

Summary:
java.lang.Class<T>的URL  getResource(String name)时可以使用参数:
(1)""

(2)以"/"开头的包路径

java.lang.ClassLoader的URL getResource(String name)时使用参数:
(1)""
(2)不以"/"开头的包路径

源码解析:

java.lang.Class

 /**
     * Finds a resource with a given name.  The rules for searching resources
     * associated with a given class are implemented by the defining
     * {@linkplain ClassLoader class 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 to {@link
     * ClassLoader#getSystemResource}.
     *
     * <p> Before delegation, an absolute resource name is constructed from the
     * given resource name using this algorithm:
     *
     * <ul>
     *
     * <li> If the {@code name} begins with a {@code ‘/‘}
     * (<tt>‘\u002f‘</tt>), then the absolute name of the resource is the
     * portion of the {@code name} following the {@code ‘/‘}.
     *
     * <li> Otherwise, the absolute name is of the following form:
     *
     * <blockquote>
     *   {@code modified_package_name/name}
     * </blockquote>
     *
     * <p> Where the {@code modified_package_name} is the package name of this
     * object with {@code ‘/‘} substituted for {@code ‘.‘}
     * (<tt>‘\u002e‘</tt>).
     *
     * </ul>
     *
     * @param  name name of the desired resource
     * @return      A  {@link java.net.URL} object or {@code null} if no
     *              resource with this name is found
     * @since  JDK1.1
     */
    public 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);
    }
   /**
     * Add a package name prefix if the name is not absolute Remove leading "/"
     * if name is absolute
     */
    private 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;
    }

从源码看:
(1)java.lang.Class的getResource(String name)方法调用了ClassLoader的getResource(String name)方法;

(2)java.lang.Class的resolveName(String name)方法去掉了name中的第一个字符“/”,

java.lang.Classloader的getResource(String name)的参数name首字母没有“/”

时间: 2024-08-10 02:36:48

根据ClassLoader获取资源文件的相关文章

Java中获取资源文件的方法总结

这里总结3中方法获取资源文件的 ServletContext Class ClassLoader 文件的位置 1. ServletContext public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = response.getWriter(); ServletContext context

servlet和普通类获取资源文件的方法

package cn.servlet.demo1; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Properties; import javax.servlet

wpf 前台获取资源文件路径问题

1 <ImageBrush ImageSource="YT.CM.CommonUI;component/Resource/FloadwindowImage/middle.png"/> YT.CM.CommonUI  这是一个类库名字 Resource 这是类库下的文件夹 FloadwindowImage 是Resource下的文件夹 middle.png 是FloadwindowImage下的一张图片 若在使用上句在wpf前台获取该类库下的文件夹中的图片资源,可能会报该路径

android 获取资源文件 R.drawable中的图片转换为drawable、bitmap(转载)

转载自:android 获取资源文件 R.drawable中的图片转换为drawable.bitmap 1. Resources resources = mContext.getResources();Drawable drawable = resources.getDrawable(R.drawable.a);imageview.setBackground(drawable); 2. Resources r = this.getContext().getResources();Inputstr

&lt;Android&gt;关于获取资源文件R中的数据

通常我们都会使用context.getResources().getIdentifier(name, type,context.getPackageName())的方法去获取R.java中的数据. type--R其中的内部类名,如"drawable","string","color","dimen","layout"等,这也是我们常用的关于界面所需要获取的数据类型. name--R内部类中的static变量

Android反编译获取资源文件-android学习之旅(69)

有时候你看到一些很好看的布局,会考虑别人怎么实现的,回想参考一下,那么这时候反编译一下是很必要的. 要用到的工具apktool.bat和aapt.exe和apktool.jar(要最新版本) 下载前两个网址是http://apktool.shoujifans.com/ apktool.jar要求是最新版,所以到官网去下载http://ibotpeaches.github.io/Apktool/ 要是嫌麻烦,就去我的网址下载,打包好了. 下载链接http://download.csdn.net/d

springboot jar包运行中获取资源文件

1. 今天晚上写了一个程序,基于Spring boot的一个小网站,发现使用FileUtils.class.getResource(path)来获取jar包中的资源文件并不能成功,其路径很奇怪 file:/Users/lonecloud/Documents/ideaCode/git/export/target/export-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/temp/temp.xls 查阅资料后,并且查看jar包中的资源文件发现有!还有classes!这

C#获取资源文件

System.Resources.ResourceManager rs = new System.Resources.ResourceManager("NetWebBrowser.Resource", typeof(Resource).Assembly);//此处的 NetWebBrowser.Resource 表示:命名空间.资源类名var title = rs.GetString("title");//获取资源名为title的字符串var img = rs.Ge

Java获取资源文件

比如我们有以下目录 |--project |--src |--javaapplication |--Test.java |--file1.txt |--file2.txt |--build |--javaapplication |--Test.class |--file3.txt |--file4.txt 在上面的目录中,有一个src目录,这是JAVA源文件的目录,有一个build目录,这是JAVA编译后文件(.class文件等)的存放目录 那么,我们在Test类中应该如何分别获得 file1.