`
liujianeye
  • 浏览: 12194 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

JAVA读取配置文件

阅读更多
package com.web.servlet.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * 读取配置文件
 * @author liujian
 *
 */
public class ReadConfigFile {

	public static void main(String[] args) throws Exception {
		//读取etc目录下的配置文件
		readJavaConfigFile();
		
		System.out.println("==============================================");
		//配置文件和java文件在同一个目录下
		readSameDirectory();
		
		System.out.println("=============================================");
		//读取etc目录下的properties配置文件
		readPropertiesFile();
		
		//读取web目录下的配置文件
		readWebDirectoryFile();
	}
	
	/**
	 * 读取etc目录下的properties配置文件
	 * @throws Exception
	 * @throws IOException
	 */
	public static void readPropertiesFile() throws Exception, IOException{
		Properties pro = new Properties();
		pro.load(new InputStreamReader(ReadConfigFile.class.getClassLoader().getResourceAsStream("config.properties"),"utf-8"));
		System.out.println(pro.get("username"));
	}
	
	/**
	 * 配置文件和java文件在同一个目录下
	 * @throws Exception
	 */
	public static void readSameDirectory() throws Exception{
		InputStream in = ReadConfigFile.class.getResourceAsStream("config.xml"); 
		if(in == null){
			System.out.println("没有找到文件");
			return;
		}
		BufferedReader bf = new BufferedReader(new InputStreamReader(in,"utf-8"));
		String str = null;
		while((str=bf.readLine())!=null){
			System.out.println(str);
		}
		in.close();
		bf.close();
	}
	
	/**
	 * 读取java目录下,etc目录下的配置文件
	 * @throws IOException
	 */
	public static void readJavaConfigFile() throws IOException{
		//如果找不到,则返回null
		InputStream in = ReadConfigFile.class.getClassLoader().getResourceAsStream("ehcache.xml");
		if(in == null){
			System.out.println("没有找到文件");
			return;
		}
		BufferedReader bf = new BufferedReader(new InputStreamReader(in,"utf-8"));
		String str = null;
		while((str=bf.readLine())!=null){
			System.out.println(str);
		}
		in.close();
		bf.close();
	}
	
	/**
	 * 读取web目录下的配置文件
	 * @throws Exception
	 */
	public static void readWebDirectoryFile() throws Exception{
		String path = ReadConfigFile.class.getResource("").getPath();
		path = path.substring(1, path.indexOf("WebRoot"));
		//读取js目录下的文件
		//InputStream in = new FileInputStream(path+"WebRoot/js/json.js");
		//读取web.xml
		InputStream in = new FileInputStream(path+"WebRoot/WEB-INF/web.xml");
		BufferedReader bf = new BufferedReader(new InputStreamReader(in,"utf-8"));
		String str = null;
		while((str=bf.readLine())!=null){
			System.out.println(str);
		}
		in.close();
		bf.close();
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics