Properties
配置文件
将properties
文件放到src
文件夹中,项目部署时会一起备份到一个路径中。
先利用context
获取到properties
文件数据流,令InputStream
接收
然后用Properties
类的load
方法转为Properties
的数据
@WebServlet("/momo")
public class MoMo extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doGet(req, resp);
ServletContext context = getServletContext();
// 获取数据流
InputStream is = context.getResourceAsStream("/WEB-INF/classes/student.properties");
Properties properties = new Properties();
// 加载成properties
properties.load(is);
// 输出 na
System.out.println(properties.getProperty("name"));
// 设置一个新数据
properties.setProperty("new", "new");
System.out.println(properties.getProperty("new"));
// 部署之后的地址其实是:
// D:\EnglishCatalog\Code\JavaWeb\JavaWeb01\out\artifacts\Test_war_exploded\WEB-INF\classes\student.properties
// 而 / 代表当前项目的地址;所以:/WEB-INF/classes/student.properties
}
}
在其他类中读取:
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Properties;
public class Test {
public static void main(String[] args) throws SQLException, IOException {
Properties properties = new Properties();
InputStream is = Test.class.getResourceAsStream("/druid.properties");
properties.load(is);
System.out.println(properties.getProperty("maxWait"));
}
}