加载资源在本地工作但不在服务器

时间:2016-04-28 19:45:40

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

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

我也在Windows服务器2008上使用相同的java版本1.8尝试了我的代码,当我将一些变量(用户名和密码)硬编码时,它可以正常工作,但是当我让代码从reousrce中读取它们时文件,它只是在我的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,我不知道你需要哪些其他信息来帮助我,但如果你说,我会给你

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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