【问题标题】:loading resource works locally but not on server加载资源在本地工作,但不在服务器上
【发布时间】:2016-04-28 19:45:39
【问题描述】:

首先,我通过在 eclipse 和我的 mac 上独立的 tomcat 8.0.33 上提取 war 文件(使用 maven)来尝试我的代码。

我还在 Windows Server 2008 上使用相同的 Java 版本 1.8 尝试了我的代码,当我将一些变量(用户名和密码)硬编码时它可以工作,但是当我让代码从资源中读取它们时文件,它只是在我的mac上工作(eclipse和tomcat都是独立的),而不是在服务器上

这是读取资源的代码

private static String getUsername() {
        Properties prop = new Properties();
        InputStream input = null;

        try {

            input = new FileInputStream(MyConfiguration.class.getClassLoader()
                    .getResource("configuration.properties").getFile());

            // load a properties file
            prop.load(input);

            // get the property value and print it out
            return prop.getProperty("username");

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

configuration.properties 的位置在src/main/resources 中,在服务器上,我可以看到该文件位于正确的目录中。

我用的是maven,不知道你还需要什么信息来帮助我,但是如果你说,我会给你

【问题讨论】:

    标签: java eclipse maven tomcat windows-server-2008


    【解决方案1】:

    你可以试试 input = Thread.currentThread().getContextClassLoader().getResourceAsStream("configuration.properties");

    【讨论】:

    • 没错,这里没有理由使用文件。当configuration.properties 捆绑在战争中时,您无法将其作为文件访问。它在您的 IDE 中工作的原因是您仍然可以将它作为文件访问。 issues.apache.org/jira/browse/SUREFIRE-855 与此相关,它现在允许您使用工件而不是类文件夹进行测试,就像“生产中”一样。
    【解决方案2】:

    打开您的战争和包含您的应用程序的 jar 文件。确保您尝试打开的资源位于正在部署的 jar(在战争中)中。大多数时候这发生在我身上,这是因为我没有告诉我的构建过程需要将该文件复制到部署中。类文件会自动运行,但并不总是资源文件。

    【讨论】:

    • 我在问题中说,它在那里,我可以看到它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多