这是你的选择。基本上有以下三种方式:
将其放入类路径中,以便您可以通过以下方式加载它ClassLoader#getResourceAsStream()
使用类路径相对路径:
Properties properties = new Properties();
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("filename.properties"));
Here filename.properties
应该放置在 web 应用程序的默认类路径覆盖的根目录之一中,例如Webapp/WEB-INF/lib
, Webapp/WEB-INF/classes
, Appserver/lib
or JRE/lib
。如果属性文件是特定于 Web 应用程序的,最好将其放在WEB-INF/classes
。如果您在 IDE 中开发项目,也可以将其放入 src 文件夹(项目的源文件夹)中。
您也可以将其放在默认类路径之外的某个位置,并将其路径添加到应用程序服务器的类路径中。例如,在 Tomcat 中,您可以将其配置为 Shared.loader 属性Tomcat/conf/catalina.properties
.
2.) 将其放在 web 文件夹(项目的 web 内容文件夹)中的某个位置,以便您可以通过以下方式加载它ServletContext#getResourceAsStream()
具有网络内容相对路径:
Properties properties = new Properties();
properties.load(getServletContext().getResourceAsStream("/WEB-INF/filename.properties"));
请注意,我已经演示了将文件放入/WEB-INF
文件夹,否则任何网络浏览器都可以公开访问它。另请注意,ServletContext
是在任何HttpServlet
类只能由继承访问GenericServlet#getServletContext()
.
3.) 将其放在本地磁盘文件系统中的某个位置,以便您可以正常加载它java.io
使用绝对本地磁盘文件系统路径的方式:
Properties properties = new Properties();
properties.load(new FileInputStream("/absolute/path/to/filename.properties");
这里有很多不同的方法,但这取决于您的需求:
从以下位置加载属性文件$TOMCAT_HOME/conf directory
你需要使用访问它java.io.File
自类加载器以来的对象(如this.getClass().getClassLoader().getResourceAsStream(...)
只能从类路径(在WEB-INF/classes
, WEB-INF/lib
or $TOMCAT_HOME/lib
).
从以下位置加载文件的最简单示例Tomcat's config directory
将会:
File configDir = new File(System.getProperty("catalina.base"), "conf");
File configFile = new File(configDir, "myconfig.properties");
InputStream stream = new FileInputStream(configFile);
Properties props = new Properties();
props.load(stream);