java - 加载资源在本地有效,但在服务器上无效

标签 java eclipse maven tomcat windows-server-2008

首先,我通过在 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,我不知道你还需要什么其他信息来帮助我,但如果你说,我会给你

最佳答案

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

关于java - 加载资源在本地有效,但在服务器上无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36924141/

相关文章:

java - 升级到 Log4J2 面临异常。 [Java.lang.ClassNotFoundException : org. apache.logging.log4j.LogManager]

java - 如何在 Linux(Ubuntu) 中安装 java

java - 在 Eclipse 中使用相同主机但不同端口运行两个 Web 应用程序

java - 使用 Maven 构建 WALA(用于分析的 Watson 库)失败

Java 我的程序的数组没有显示任何值

java - 如何从资源文件夹加载文件?

java - 遇到这个java代码的问题 - 应该打印并计算随机抛硬币中正面和反面的数量

java - JFormattedTextField 接受不同位数的数字

java - 导入java.awt无法解析

java - Maven 依赖项在 primefaces 中不起作用?