java 读取配置文件

来源:互联网 发布:怎样建立切片软件 编辑:程序博客网 时间:2024/05/17 20:53

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 voidmain(String[] args) {
      //获取目录路径(App程序下获取方法)
      String path = newTest().getClass().getResource("/").getPath();
      //获取目录路径(Web程序下获取方法)
      //  String path = newTest().getClass().getProtectionDomain().getCodeSource() 
      //       .getLocation().getPath();
      //  if (path.indexOf("WEB-INF")> 0) { 
      //    path= path.substring(0, path.indexOf("WEB-INF") +8); 
      //  } else{ 
      //   throw newIllegalAccessException("路径获取错误"); 
      //  
      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