Java读取ini文件和中文乱码问题解决

时间:2025-02-13 18:21:23

提出问题:

初用properties,读取java properties文件的时候如果value是中文,会出现读取乱码的问题 。

问题分析:

最初认为是文件保存编码问题,于是进行编码的统一:

1)把MyEclipse中所有的文件编码都修改成UTF-8,问题仍然存在;

2)把内容复制到EditPlus进行UTF-8编码转换,问题仍然存在

3)上网搜索有人提议重写properties类或者用jdk自带的编码转换工具,非常麻烦而且不可取,Java的开发者可定会考虑到编码问题;最初的方法如下:

/**
* 读取配置文件
* @param filePath配置文件的路径
*/
public static Properties readFileByStream(String filePath){
filePath = getRealPath(filePath);//获取文件的绝对路径
/**定义变量*/
FileInputStream fileInput = null;//读
       Propertiesproper = new Properties();  
     try {
fileInput = new FileInputStream(filePath);
(fileInput);  
} catch (FileNotFoundException e) {
();
} catch (IOException e) {
();
}  
    return proper;
}

这个方法用的是字节流来读取文件,中文会乱码;

因为字节流是无法读取中文的,所以采取把FileInputStream转换成InputStreamReader用字符流来读取中文。代码如下:

/**
* 读取配置文件
* @param filePath文件的路径
*/
public static Properties readFileByReader(String filePath){
/**定义变量*/
InputStream inputStream = ().getResourceAsStream(filePath);  
  Propertiesproper = new Properties();  
    try {
    BufferedReader bf = new BufferedReader(new  InputStreamReader(inputStream));  
(bf);  
} catch (FileNotFoundException e) {
();
} catch (IOException e) {
();
}  
    return proper;
}


不再乱码了

为了方便查看,贴出完整代码:

public class ConfigFile {
	public static final String configFile = "/config/";		//配置文件的路径
	
	/**
	 * 获取文件中的某一项的值
	 * @param key
	 * @return
	 */
	public static String getKey(String key){
		Properties proper = readFileByReader(configFile);
		return (key);
	}
	
	/**
	 * 字节流读取配置文件
	 * @param filePath
	 */
	public static Properties readFileByStream(String filePath){
		filePath = getRealPath(filePath);
		/**定义变量*/
		FileInputStream fileInput = null; 		//读
	    Properties proper; 
	    
	    proper = new Properties();  
	    try {
			fileInput = new FileInputStream(filePath);
			(fileInput);  
		} catch (FileNotFoundException e) {
			();
		} catch (IOException e) {
			();
		}  
	    return proper;
	}
	
	/**
	 * 字符流读取配置文件
	 * @param filePath
	 */
	public static Properties readFileByReader(String filePath){
		/**定义变量*/
		InputStream inputStream = ().getResourceAsStream(filePath);  
	    Properties proper; 
	    
	    proper = new Properties();  
	    try {
	    	BufferedReader bf = new BufferedReader(new  InputStreamReader(inputStream));  
			(bf);  
		} catch (FileNotFoundException e) {
			();
		} catch (IOException e) {
			();
		}  
	    return proper;
	}
	
	/** 获取类根路径 */
	public static String getClassRoot(){
		return ("/").getPath().substring(1);
	}
	
	/** 获取相对路径的真实的路径 */
	public static String getRealPath(String path){
		if((0) == '/'){
			path = getClassRoot() + (1);
		}else if((1) != ':'){
			path = getClassRoot() + path;
		}
		return path;
	}
	
	/**
	 * 测试
	 */
	public static void main(String[] args) {
		(getKey("welcome_message"));
		(0);
	}
}