下面的代码在 Tomcat 中运行良好,但在 WebSphere 6.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?

最佳答案

我猜想区别在于 ClassLoader 的行为方式。您可以改用 Class 变体吗?我的课。 class.getResource() ?我们一直在 WebSphere 6.1 下使用 Class.getResourceAsStream()

或者尝试在您的资源路径前使用前导斜杠。

使用 Class 变体,您的相对路径将在 resources 包下的 MyClass 子目录中查找。但 ClassLoader 变体可能不会。

关于java - 如何在 WebSphere 6.1 中正确获取类路径上资源的 URL?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9507419/

10-10 14:04