Java 应用程序 访问配置文件

来源:互联网 发布:java 模拟post请求 编辑:程序博客网 时间:2024/06/12 18:17

Java应用程序经常要访问配置文件,比如读取数据库的信息。下面是读取配置文件的代码,配置文件放到工程的根目录下,src文件夹外面即可。这样,等到程序大包成可运行Jar的时候,配置文件还是在jar的外面,方便运行的时候修改配置文件,而不是打包时就已经写死了。

package org.scutemos.util;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.util.Properties;import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class PropertyReader {private static Logger logger = LoggerFactory.getLogger(PropertyReader.class);private static int serverPort=0;private static String jdbc_driver = "";private static String db_url="";private static String db_user="";private static String db_password="";private static String path ="clientUpdate.properties";private static Properties props;static{Properties props = new Properties();FileInputStream inputFile = null;try {inputFile = new FileInputStream(path);props.load(inputFile);} catch (IOException e) {e.printStackTrace();} finally {try {inputFile.close();} catch (IOException e) {e.printStackTrace();}}}private static void readProperty(){Properties props = new Properties();FileInputStream inputFile = null;try {inputFile = new FileInputStream(path);props.load(inputFile);} catch (IOException e) {e.printStackTrace();} finally {try {inputFile.close();} catch (IOException e) {e.printStackTrace();}}serverPort = Integer.parseInt(props.getProperty("serverPort"));jdbc_driver = props.getProperty("JDBC_DRIVER");db_url = props.getProperty("DB_URL");db_user = props.getProperty("DB_USER");db_password = props.getProperty("DB_PASSWORD");}public static String getJdbcDriver() {if(jdbc_driver==null || "".equals(jdbc_driver)){readProperty();if(jdbc_driver==null || "".equals(jdbc_driver)){logger.error("JDBC_DRIVER must be written to db.conf");System.exit(1);}}return jdbc_driver;}public static String getDbUrl() {if(db_url==null || "".equals(db_url)){readProperty();if(db_url==null || "".equals(db_url)){logger.error("DB_URL must be written to db.conf");System.exit(1);}}return db_url;}public static String getDbUser() {if(db_user==null || "".equals(db_user)){readProperty();if(db_user==null || "".equals(db_user)){logger.error("DB_USER must be written to db.conf");System.exit(1);}}return db_user;}public static String getDbPassword() {if(db_password==null || "".equals(db_password)){readProperty();if(db_password==null || "".equals(db_password)){logger.error("DB_PASSWORD must be written to db.conf");System.exit(1);}}return db_password;}public static int getPort(){if(serverPort==0 ){readProperty();if(serverPort==0 ){logger.info("serverPort must be writen to communication.properties.");System.exit(1);}}return serverPort;}}


0 0
原创粉丝点击