如果A类(捆绑在
A.jar中)想要从jar中加载xml并尝试以第一个代码示例中所示的方式访问xml,那么它将无法
p.xml在jar中访问。它访问该位置的文件。
很容易测试是否属于您的情况。创建jar之后,暂时p.xml从文件系统中删除并运行A类。它将无法加载。
当类需要加载捆绑在jar中的资源时,它不使用,File而是使用类加载器。
根据您提供的名称,我假设您的类A在软件包中:
com.stackoverflow.A xml文件在软件包中
com.stackoverflow.A.res
以下所有方法将使用您的xml加载流
InputStream is = null;// Using class - relative to the class location because path does not start with "/"is = SimpleWriter.class.getResourceAsStream("res/p.xml");// Using class - absolute path because path starts with "/"is = SimpleWriter.class.getResourceAsStream("/com/stackoverflow/A/res/p.xml");// Using classloader - path is *always* absolute. Note that leading "/" is missingis = SimpleWriter.class.getClassLoader().getResourceAsStream("com/stackoverflow/A/res/p.xml");


