java基础之Properties

来源:互联网 发布:elvis elvin 知乎 编辑:程序博客网 时间:2024/05/01 10:59
package com.j2se.propertiesDemo;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.util.Properties;/* * 学习properties:类似于map集合,以键值对的形式存储数据 */public class PropertiesDemo {public static void main(String[] args) throws Exception{//printDemo();printCountDemo();}/** * 打印出文本文件中的内容:前提是配置文件以键值对的形式存储 */public static void printDemo()throws Exception{File file=new File("src/demo.txt");Properties properties= new Properties();properties.load(new FileInputStream(file));String name= properties.getProperty("name");String gender=properties.getProperty("gender");String age=properties.getProperty("age");System.out.println("age="+age);//配置文件加载到内存中,我们修改的只是内存中的properties,并没有作用到文件中properties.setProperty("age", "23");FileOutputStream fos=new FileOutputStream(file);properties.store(fos, "这是注释");System.out.println(properties);}/** * 实现计数器效果:properties配置文件中是应用程序共享的效果。 * 在web程序中,当应用程序停止时,将当前count计数器的数据保存到配置文件中,下次启动运行时有自动加1 * 下面我们可以写一个计数器来实现注册次数不能超过5次 */public static void printCountDemo() throws Exception{File file=new File("src/count.ini");if(!file.exists()){file.createNewFile();}FileInputStream fis=new FileInputStream(file);Properties properties=new Properties();properties.load(fis);int counter=0;String count= properties.getProperty("counter");if(count!=null){counter=Integer.parseInt(count);if(counter>=5){System.out.println("亲,对不起,您注册已经超过5次");return;}}counter++;properties.store(new FileOutputStream(file), "这是计数器");fis.close();}}

0 0
原创粉丝点击