Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何正确获取WebSphere6.1中类路径上资源的URL?_Java_Websphere_Classpath_Classloader - Fatal编程技术网

Java 如何正确获取WebSphere6.1中类路径上资源的URL?

Java 如何正确获取WebSphere6.1中类路径上资源的URL?,java,websphere,classpath,classloader,Java,Websphere,Classpath,Classloader,下面的代码在Tomcat中运行良好,但在WebSphere6.1中对getResource(…)的调用返回null。我尝试使用Thread.currentThread().getClassLoader()和MyClass.class.getClassLoader()-两者都返回null URL url = null; ClassLoader cl = MyClass.class.getClassLoader(); LOG.info("Using class's class

下面的代码在Tomcat中运行良好,但在WebSphere6.1中对getResource(…)的调用返回null。我尝试使用Thread.currentThread().getClassLoader()和MyClass.class.getClassLoader()-两者都返回null

    URL url = null;
    ClassLoader cl = MyClass.class.getClassLoader();
    LOG.info("Using class's classloader.");

    url = cl.getResource("resources/AConfigFile.xml");

    if(url == null) {
        throw new RuntimeException("The ClassLoader returned null for the URL of the " +
                "the XML Document.  This is definitely not right.");
    }
…我也试过这个,但运气不好

   URL url = null;

    url = MyClass.class.getResource("resources/AConfigFile.xml");

    if(url == null) {
        throw new RuntimeException("The ClassLoader returned null for the URL of the " +
                "the XML Document.  This is definitely not right.");
    }

这是怎么回事?如何正确获取类路径上资源的URL?

我想区别在于
类加载器的行为方式。您可以改用
变量吗?我的班级。?我们一直在WebSphere6.1下使用
Class.getResourceAsStream()

或者可以尝试在资源路径的前面加一个斜杠


使用
Class
变量,您的相对路径将在
MyClass
包下的
resources
子目录中查找。但是
类加载器
变量可能不会。在servlet容器中,应该分别使用and而不是and。它更有可能在不同的servlet容器中保持一致的行为


此外,再次检查您的相对路径在您使用它的上下文中是否正确。尝试使用绝对路径,看看效果是否更好。

我已经尝试了类变量。不走运。但是我已经花了很多钱在前面的斜杠上解决了这个问题…现在重建以测试…我们很快就会发现:)“这个方法与java.lang.Class.getResource有不同的用途,后者基于类加载器查找资源。这个方法不使用类加载器。”
Class
方法在WebSphere中肯定有效。@dbreaux:
Class
方法可能对您“有效”,但如果您正在加载web应用程序中的资源,建议使用
ServletContext
中的方法。这就是它们的设计目的。事实证明,前导斜杠足以帮助容器找到资源,从而解决了OP的问题。但我仍然建议切换到
ServletContext
方法。