inireader.java

来自「为公司做的质量考核接口源码,用spring,hibernate,XML实现,对X」· Java 代码 · 共 81 行

JAVA
81
字号
/**
 * 
 */
package com.jr81.common;


import  java.io.BufferedReader;
import  java.io.FileNotFoundException;
import  java.io.FileReader;
import  java.io.IOException;
import  java.util.HashMap;         
import  java.util.Properties;       

public   class   IniReader   {     

	protected   HashMap   sections   =   new   HashMap();   
	private   transient   String   currentSecion;     
	private   transient   Properties   current;     

	public   IniReader(String   filename) {     
		try {
			BufferedReader   reader   =   new   BufferedReader(new   FileReader(filename));     
			read(reader);     
			reader.close();
		} catch (FileNotFoundException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}     
	}     

	protected   void   read(BufferedReader   reader)   throws   IOException   {     
		String   line;     
		while   ((line   =   reader.readLine())   !=   null)   {     
			parseLine(line);     
		}     
	}     

	protected   void   parseLine(String   line)   {     
		line   =   line.trim();     
		if   (line.matches("\\[.*\\]"))   {     
			currentSecion   =   line.replaceFirst("\\[(.*)\\]",   "$1");     
			current   =   new   Properties();     
			sections.put(currentSecion,   current);   
		}   else   if   (line.matches(".*=.*"))   {     
			if   (current   !=   null)   {   
				int   i   =   line.indexOf('=');     
				String   name   =   line.substring(0,   i);     
				String   value   =   line.substring(i   +   1);     
				current.setProperty(name,   value);     
			}     
		}     
	}     

	public   String   getValue(String   section,String		name,String def)   {     
		Properties   p   =   (Properties)   sections.get(section);     

		if   (p   ==   null)   {     
			return   null;     
		}     

		String   value   =   p.getProperty(name);    
		if (value==null) value=def;
		return   value;     
	}  

	public   String   getValue(String   section,String		name)   {
		return getValue(section,name,"");
	}

	public static void main(String[] p){
		IniReader ir=new IniReader("c:\\1.ini");
		System.out.println(ir.getValue("System","DBName"));
		System.out.println(ir.getValue("Font","Name"));
		System.out.println(ir.getValue("System","UserNam1e"));		        	 
	}
 
} 

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?