資源負載可以在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");