zoukankan      html  css  js  c++  java
  • java.util.Properties读取中文内容的配置文件,发生中文乱码的现象有解决方案

    本来没啥好说的,但是网上流传的关于那个绕弯方法的文章太多了,太误导人了,还是写一下以正视听吧。

    直接上源码

     -------------------------------------------------------

    package com.igrslab.spider.util;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.Reader;
    import java.util.Properties;
    public class MyConfig {
    	private static Properties props = new Properties();
    	private static MyConfig instance=null;
    	private static Reader reader = null;
    	
    	public static synchronized MyConfig getInstance(){
    		if(instance==null){
    			instance=new MyConfig();
    		}
    		return instance;
    	}
    	
    	private MyConfig(){
    		init();
    	}
    	private void init(){
    		try {
    			reader = new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"), "UTF-8");//编码
    			props.load(reader);  
    		}  catch (FileNotFoundException e1) {
    			System.err.println("config.properties is not in the classpath. Please check it.");
    			return;
    			// e1.printStackTrace();
    		}catch (Exception e) {
    			e.printStackTrace();
    			return;
    		}finally{
    			if (null != reader){
    				try {
    					reader.close();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    		}
    	}
    	
    	public String getValue(String param){
    		return props.get(param)==null?null:String.valueOf(props.get(param)).trim();
    	}
    	
    	public int getIntValue(String param){
    		int value=0;
    		Object obj=props.get(param);
    		if(obj!=null){
    			try{
    				String temp=obj.toString();
    				value=Integer.valueOf(temp.trim());
    			}catch(Exception ex){
    				ex.printStackTrace();
    			}
    		}
    		return value;
    	}
    	public long getLongValue(String param){
    		long value=0;
    		Object obj=props.get(param);
    		if(obj!=null){
    			try{
    				String temp=obj.toString();
    				value=Long.valueOf(temp.trim());
    			}catch(Exception ex){
    				ex.printStackTrace();
    			}
    		}
    		return value;
    	}
    	public boolean getBooleanValue(String param){
    		boolean value=false;
    		Object obj=props.get(param);
    		if(obj!=null){
    			try{
    				String temp=obj.toString();
    				value=Boolean.valueOf(temp.trim());
    			}catch(Exception ex){
    				ex.printStackTrace();
    			}
    		}
    		return value;
    	}
    }
    

      使用这种方法要注意一下,在linux下开发的.properties,如果要用到windows上,可能发生配置项丢失的现象。

  • 相关阅读:
    Milk Patterns POJ
    Musical Theme POJ
    iOS
    iOS
    iOS
    iOS
    iOS
    iOS
    runloop
    OC -网络请求
  • 原文地址:https://www.cnblogs.com/nevergiveupblog/p/3386446.html
Copyright © 2011-2022 走看看