java 读取配置文件

本文提供了一个Java代码示例,展示如何读取配置文件并获取特定属性值。

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

java 读取配置文件  直接上代码

java代码

package test;

import java.io.FileInputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Properties;

public class Test {
  
   public static void main(String[] args) {
       //获取目录路径(App程序下获取方法)
       String path = new Test().getClass().getResource("/").getPath();
       //获取目录路径(Web程序下获取方法)
       //  String path = new Test().getClass().getProtectionDomain().getCodeSource() 
       //       .getLocation().getPath();
       //  if (path.indexOf("WEB-INF") > 0) { 
       //    path = path.substring(0, path.indexOf("WEB-INF") + 8); 
       //  } else { 
       //   throw new IllegalAccessException("路径获取错误"); 
       //  
       FileInputStream fileInputStream = null;
       Properties properties = null;
       try {
            //获取文件路径
            String filepath = MessageFormat.format("{0}{1}",
                          path, "db2-comfig.properties");
            //System.out.println(filepath);
            filepath = java.net.URLDecoder.decode(filepath, "utf-8");
            fileInputStream = new FileInputStream(filepath);
            properties = new Properties();
            properties.load(fileInputStream);
            //获取文件中的属性(db2url为文件属性)的值
            String DB2url = properties.getProperty("db2url");
            //System.out.println(DB2url);
       } catch (Exception e) {
            e.printStackTrace();
       } finally {
            //用完关闭输出流
            properties.clear();
            properties = null;
            try {
                fileInputStream.close();
            } catch (IOException e) {

                e.printStackTrace();
            }
            fileInputStream = null;
       }
   }
}

 

db2-comfig.properties 配置文件内容

 

db2url =jdbc:db2://192.168.1.1:8080/orcl

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值