首先,我通过在 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/