首页

在java中关于properties文件类型的定义及实例分析

标签:java,properties,native2ascii,java工具,properties文件读写     发布时间:2015-06-08   

前言

在java中使用Properties类对properties文件进行读写,该文件类型是“键-值”形式进行存放,在读写文件时,使用ISO-8859-1编码,所有字符是Latin字符,对于中文需要转码后进行读写,否则会出现乱码,在jdk的bin目录下面提供native2ascii.exe将中文进行转码,如下图1-1所示。

在java中关于properties文件类型的定义及实例分析

图1-1

一、读配置文件

/**@b@ * 根据指定key读取value@b@ * @param fileName@b@ * @param key:属性名称@b@ * @retrun:属性值@b@ */@b@ pubic String  read(String fileName,String key){@b@    Properties props=new Properties():@b@    try{@b@        props.load(this.getClass().getClassLoader().getResourceAsSTream(fileName));@b@        String n=props.getProperty(key);@b@        System.out.println(n);@b@        return n;@b@    }catch(Exception e){@b@        e.printStackTrace@b@        return nll;@b@    }@b@@b@}@b@@b@public void readProperties(String fileName){@b@    Properties props=new properties();@b@@b@try{@b@        props.load(this.getClass().getClassLoader().getResourceAsSTream(fileName));@b@        String n=props.getProperty(key);@b@        System.out.println(n);@b@        return n;@b@    }catch(Exception e){@b@        e.printStackTrace@b@        return nll;@b@    }@b@    @b@ public  void readProperties(String fileName ){@b@     Properties props=new Properties();@b@     try{@b@         Enumeration en=props.propertyName;@b@         while(en.hasMoreElement){@b@             String key=(String)en.nextElemnent();@b@             System.out.println(key+":"+props.getProperty(key));@b@         }@b@     }catch(Exception e){}   @b@ }

二、写配置文件

/**@b@ * 根据指定key读取value@b@ * @param fileName@b@ * @param parameterName:属性名称@b@ * @param:parameterValue属性值 */@b@ public void writeProperties(String fileName,String parameterName,String parameterValue){@b@     @b@     Properties prop=new Properties();@b@     String path=this.getClass().getClassLoader().getResource("").getPath().substring(1);@b@     path=path+fileName;@b@     System.out.println(fileName);@b@     try{@b@         InputStream fis=new FileInputStream(path);@b@         prop.load(fis);@b@         OutputStream fos=new FileOutputStream(path);@b@         prop.setProperty(paramerterName,parameterValue);@b@         prop.store(fos,"Update"+parameterName+"value");@b@         @b@     }catch(Exception e){@b@     }@b@ }