【Java】【22】读写properties文件

token.properties

jsapi_ticket=1
access_token=2

读写文件

public class PropertiesUtil {
    private static Logger logger = Logger.getLogger(PropertiesUtil.class.getName());
     /** 
     * 根据KEY,读取文件对应的值 
     * @param filePath 文件路径,即文件所在包的路径,例如:java/util/config.properties 
     * @param key 键 
     * @return key对应的值 
     */  
    public static String readData(String filePath, String key) {  
        Properties props = new Properties(); 
        //获取绝对路径  
        filePath = PropertiesUtil.class.getResource("/" + filePath).toString();  
        //截掉路径的"file:"前缀  
        filePath = filePath.substring(6);    
        try {  
            InputStream in = new BufferedInputStream(new FileInputStream(filePath));  
            props.load(in);  
            in.close();  
            String value = props.getProperty(key);  
            return value;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return null;  
        }  
    }  
    
    /** 
     * 修改或添加键值对 如果key存在,修改, 反之,添加。 
     * @param filePath 文件路径,即文件所在包的路径,例如:java/util/config.properties 
     * @param key 键 
     * @param value 键对应的值 
     */ 
    public  synchronized static void writeData(String filePath, String key, String value) {          
        OutputStream fos=null;
        Properties prop = new Properties();  
        filePath = PropertiesUtil.class.getResource("/" + filePath).toString(); //获取绝对路径                   
        filePath = filePath.substring(6);//截掉路径的"file:/"前缀          
        logger.info("绝对路径:"+filePath); 
        
        try {  
            logger.info("begin writeData");
            File file = new File(filePath);   
            InputStream fis = new FileInputStream(file);  
            prop.load(fis);               
            fis.close(); //一定要在修改值之前关闭fis 
            fos = new FileOutputStream(filePath);  
            prop.setProperty(key, value);  
            //保存,并加入注释  
            prop.store(fos, String.format("update %s value", key));                                    
        } catch (IOException e) {        
            logger.info("修改文件报错:" + e);
        }  
        
        finally
        {
             try {
                fos.close();// fos.close(); 
              } catch (IOException e) {
                  logger.info("关闭报错:" + e);
             } 
        }
       
    }  
}

猜你喜欢

转载自www.cnblogs.com/huashengweilong/p/10924628.html