Resouceutils.getfile cannot get resource file source summary in jar

Source: Internet
Author: User
Tags assert

Original: https://www.cnblogs.com/chyu/p/8407541.html

Spring provides a tool class to load files under Classpath, generally without problems, but when it loads a file in a jar package as a tool in a public jar package, it reports an error that the file cannot be found.

Click on the source of the tool class Resouceutils.getfile () method:

public static File GetFile (String resourcelocation) throws FileNotFoundException {Assert.notnull (resourcelocation
        , "Resource location must is not NULL"); if (Resourcelocation.startswith (Classpath_url_prefix)) {String path = resourcelocation.substring (Classpath_ur
            L_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 Resol
            Ved to absolute file path because it does not exist ");
        Return getFile (URL, description);
        try {//try URL return GetFile (New URL (resourcelocation));
   The catch (Malformedurlexception ex) {//no URL-> treat as file path         return new File (resourcelocation); }
    }

Look at the structure of the Code simple logic clear, there may be a problem is the icon Red 2. Here my first impression was that the class loader did not load the resource when it was loaded. Debug the class loader for Cl.getresource (path) is

WebappClassLoader, want to look at the internal implementation, but here will not go in, and then Baidu found this is jetty realize their own classloader, intercept some of the key loading source:

public void Addjars (Resource lib)  {  
    if (lib.exists () && lib.isdirectory ())  
    {  
        string[] files= Lib.list ();
        for (int f=0;files!=null && f<files.length;f++)  {  
            try {  
                Resource Fn=lib.addpath (files[f]);
                String fnlc=fn.getname (). toLowerCase ();  
                if (Fnlc.endswith (". Jar") | | fnlc.endswith (". zip"))  {  
                    String jar=fn.tostring ();    
                    Jar=stringutil.replace (Jar, ",", "%2c");  
                    Jar=stringutil.replace (jar, ";", "%3b");  
                    Addclasspath (jar);  
                }  
            }  catch (Exception ex) {  
                log.warn (LOG.EXCEPTION,EX);  
            }  
        }  
    }  

The above piece is the part of the source that adds the jar and zip path to the classpath of the ClassLoader. Continue to debug

URL url = (cl!= null Cl.getresource (PATH): Classloader.getsystemresource (path));

The above URL results:

The path to the file being loaded is actually taken, because the Protocol field is identified as a jar in the jar package. It doesn't look like this. The load file that was caused by the class loader failed. Then you have to continue to debug down to see the source code of GetFile ():

The public static File GetFile (URL resourceurl, String description) throws FileNotFoundException {
        Assert.notnull ( ResourceUrl, "Resource URL must not being null");
        if (! Url_protocol_file.equals (Resourceurl.getprotocol ()) {  //url_protocol_file= "FILE"
            throw new  FileNotFoundException (
                    description + "cannot is 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 URL that is are not valid URIs (should hardly ever).
            return new File (Resourceurl.getfile ());
        }
    

See here a little bit of language, the above part of the red font to actually determine whether the resource path of the protocol is file, because in the jar package, the protocol is a jar, so here directly throw the file did not find the exception,

Suddenly feel very silly, debug so long, and again the class loading process, in fact, the problem is very simple a problem, resouceutils.getfile () is specifically used to load uncompressed and jar package file types of resources, so it does not

To try to load the files in the jar, you can load the files in the jar by loading them in a way that reads the files in the jar, such as Xx.class.getClassLoader (). Getresouceasstream () The way to read a file as a stream.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.