在Java中,您可以使用相同的API但使用不同的URL协议加载所有类型的资源:
file:///tmp.txt
http://127.0.0.1:8080/a.properties
jar:http://www.foo.com/bar/baz.jar!/COM/foo/Quux.class
Run Code Online (Sandbox Code Playgroud)
这很好地将资源的实际加载与需要资源的应用程序分离,并且由于URL只是一个String,因此资源加载也很容易配置.
是否有使用当前类加载器加载资源的协议?这与Jar协议类似,不同之处在于我不需要知道资源来自哪个jar文件或类文件夹.
Class.getResourceAsStream("a.xml")当然,我可以使用它,但这需要我使用不同的API,因此更改现有代码.我希望能够在所有我可以通过更新属性文件指定资源URL的地方使用它.
我有一个简单的java应用程序,它从当前包中加载属性文件.
this.getClass().getResourceAsStream("props.properties");
Run Code Online (Sandbox Code Playgroud)
当我想要的属性文件在当前包中时,这可以正常工作.但是,我想将此应用程序打包为JAR,并使用我使用它的新属性文件定义和覆盖.有没有办法加载类路径上名为"props.properties"的第一个资源?
我希望通过命令行轻松覆盖属性文件:
java.exe -classpath props.properties;myJar.jar com.test.MyApp
Run Code Online (Sandbox Code Playgroud)
我不想解压缩JAR并修改属性文件来改变一些东西.我觉得我错过了一些明显的东西......
我有一个项目A,它包含一些java文件和一个类路径资源R.txt.在项目中我使用ClassLoader.getSystemResource("R.txt"); 检索R.txt.
然后我有一个项目B,其中包含项目A的jar文件.现在getSystemResource("R.txt")找不到文本文件(是的,它仍然在jar文件的根目录中).即使尝试在其他网站上建议的"/R.txt"也行不通.有任何想法吗?
我尝试使用servlet的相对路径访问WebContent/alerts文件夹中的html文件.但我无法使用其相对路径访问它,

使用相对路径从Servlet访问WebContent内的文件:
protected Element getSummary(String value) throws IOException
{
Element element=null;
Summary summary = Summary.valueOf(value);
switch(summary) {
case rtp_summary:
element=parseDIV(new File("../../WebContent/alerts/rtp_bcklg_mail.html"),"rtp_summary");
break;
case ffu_summary:
element=parseDIV(new File("/../../WebContent/alerts/ffu_comp_bcklg_mail.html"),"ffu_summary");
break;
default:
System.out.println("Enter a valid choice");
break;
}
return element;
}
Run Code Online (Sandbox Code Playgroud)
使用相对路径从Java Thread访问WebContent内的文件:
public class WriteJSONFile implements Runnable{
WriteJSONFile(){
}
@Override
public void run()
{
try {
createJSONFile();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private static void createJSONFile() throws IOException
{
String path="C:/Users/Thiru/Documents/Website Design/Macaw/";
JSONArray jsonArray=new JSONArray(); …Run Code Online (Sandbox Code Playgroud) java ×4
classloader ×1
classpath ×1
jar ×1
jsoup ×1
resources ×1
servlet-3.0 ×1
servlets ×1
url ×1