Properties配置文件

该博客讲述了如何在JavaWeb项目中读取并修改Properties配置文件。通过使用ServletContext获取资源流,加载student.properties文件,然后使用Properties类进行操作,如读取属性和设置新属性。在另一个类中,同样利用getResourceAsStream方法读取druid.properties文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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"));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值