2016-06-09 56 views
0

因此,我正在使用HTML,CSS和AngularJS的基本Web應用程序,並且我已經開始爲Spring添加功能。當我添加了幾個JAR,我開始得到錯誤 DEBUG DefaultFileSystem - Could not locate file config.xml at null: no protocol: config.xml 看來它無法找到我的config.xml文件,它目前在src/main/resources,但我試過其他地址。我在哪裏可以設置我擁有該文件的路徑,而不是它是null找不到文件config.xml爲空:無協議:config.xml - 如何設置config.xml的路徑

回答

0

資源負載可以在Java會非常棘手,下面的類將加載資源,你在桌面,網絡,classpath中,或當前的工作目錄:

package test; 

import java.io.File; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.MalformedURLException; 
import java.net.URL; 

public class JKResourceLoader { 

    public InputStream getResourceAsStream(String resourceName) { 
     URL url = getResourceUrl(resourceName); 
     if (url != null) { 
      try { 
       return url.openStream(); 
      } catch (IOException e) { 
       throw new RuntimeException(e); 
      } 
     } 
     return null; 
    } 

    public URL getResourceUrl(String fileName) { 
     if (fileName == null) { 
      return null; 
     } 
     URL resource = getClass().getResource(fileName); 
     if (resource == null) { 
      resource = Thread.currentThread().getContextClassLoader().getResource(fileName); 
      if (resource == null) { 
       resource = ClassLoader.getSystemResource(fileName); 
       if (resource == null) { 
        File file = new File(fileName); 
        if (file.exists()) { 
         try { 
          resource = file.toURI().toURL(); 
         } catch (MalformedURLException e) { 
          throw new RuntimeException(e); 
         } 
        } 
       } 
      } 
     } 
     return resource; 
    } 
} 

此外,您還可以通過使用我的jk-util項目包括Maven的依賴關係如下:

<dependency> 
    <groupId>com.jalalkiswani</groupId> 
    <artifactId>jk-util</artifactId> 
    <version>0.0.9</version> 
</dependency> 

並調用下面的代碼:

InputStream in = JKResourceLoaderFactory.getResourceLoader().getResourceAsStream("/config.xml");