现有如下结构的工程:
如果想要在 Servlet 中读取 test.properties
,有通过如下三种方式:
package com.zze.servlet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class TestServletBak extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
func1();
func2();
func3();
}
private void func1() {
try {
ServletContext servletContext = getServletContext();
// 参数传入相对路径:相对工程部署在 tomcat 下的工程根目录
InputStream inputStream = servletContext.getResourceAsStream("file/test.properties");
Properties properties = new Properties();
properties.load(inputStream);
String name = properties.getProperty("name");
System.out.println(String.format("from func1:%s", name));
} catch (IOException e) {
e.printStackTrace();
}
}
private void func2() {
try {
ServletContext servletContext = getServletContext();
// 参数传入相对路径:相对工程部署在 tomcat 下的工程根目录
String realPath = servletContext.getRealPath("file/test.properties");
FileInputStream inputStream = new FileInputStream(realPath);
Properties properties = new Properties();
properties.load(inputStream);
String name = properties.getProperty("name");
System.out.println(String.format("from func2:%s", name));
} catch (IOException e) {
e.printStackTrace();
}
}
private void func3() {
try {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("../../file/test.properties");
Properties properties = new Properties();
properties.load(inputStream);
String name = properties.getProperty("name");
System.out.println(String.format("from func3:%s", name));
} catch (Exception e) {
e.printStackTrace();
}
}
}
评论区