java Properties类

来源:互联网 发布:电视体育直播软件 编辑:程序博客网 时间:2024/04/29 04:45
/*演示:如何将流中的数据存储到集合中想要将info.txt中键值数据存到集合中进行操作。思路:1,用一个流和properties.txt文件关联。2,读取一行数据,将该行数据用“=”进行分割。3,等号左边作为键,右边作为值,存到Properties集合中。注意:对于split函数,如果分隔符为“.”或“|”或“+”等本身为转义字符时,要使用转义字符\\即,str.split("\\.");str.split("\\|");*/import java.io.*;import java.util.*;class  PropertiesTest{public static void main(String[] args) throws IOException{method();}public static void method() throws IOException{BufferedReader br=new BufferedReader(new FileReader("D:\\myfile\\mycode\\properties.txt"));FileOutputStream fos=new FileOutputStream("D:\\myfile\\mycode\\properties.txt",true);Properties prop=new Properties();String line=null;while((line=br.readLine())!=null){sop(line.split("\\+")[0]);String key=line.split("\\+")[0];String value=line.split("\\+")[1];prop.setProperty(key,value);}prop.store(fos,"haha");sop(prop);br.close();fos.close()}public static void sop(Object obj){System.out.println(obj);}}


/*配置文件,统计程序运行的次数,当程序运行一定的次数后,提示不能再使用.注意Properties类中的几个方法:load(InputStream inStream);// 从输入流中读取属性列表(键和元素对)。store(OutputStream outStream,String comments);// 以适合使用 load(InputStream) 方法加载到 Properties 表中的格式,//将此 Properties 表中的属性列表(键和元素对)写入输出流。//其中comments是注释。*/import java.io.*;import java.util.*;class RunCount {public static void main(String[] args) throws IOException{runCount();}public static void runCount() throws IOException{File file=new File("D:\\myfile\\mycode\\count.ini");if(!file.exists())file.createNewFile();FileInputStream fis=new FileInputStream(file);Properties prop=new Properties();prop.load(fis); //将读取的目标文件加载到属性对象中int count=0;String value=prop.getProperty("time");if(value!=null){count=Integer.parseInt(value);if(count>=5){System.out.println("运行次数已大于5次");return ;}}count++;prop.setProperty("time",count+"");FileOutputStream fos=new FileOutputStream(file);prop.store(fos,"");//将属性对象中的内容存储到输出文件中fis.close();fos.close();}}


0 0
原创粉丝点击