【java基础:集合与IO】Properties集合与IO流相结合进行数据读取和存储的demostration 一时失言乱红尘 2022-06-06 13:11 137阅读 0赞 package properities; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Properties; public class GetAPPCountTest { public static void main(String[] args) throws IOException { int time=10; getAppCount(time); } /* * 需求:检测某运行程序10次后,就提醒用户进行注册并且退出程序。 * 1、首先运行程序的时候就加载配置信息(配置信息记录了程序运行的次数); * 2、对加载的配置文件进行读取并将计数器加一,并且展示出当前运行的次数;如果计数到某一个值后就抛出异常。 * 3、将改变后的配置信息存储到之前的配置文件中。 */ public static void getAppCount(int time) throws IOException { File file=new File("properties.ini");//注意java的配置文件可写成".properties",ini在windows系统或者很多软件中常用。 if(!file.exists()) { file.createNewFile(); } //接下来创建Properties集合,运用IO流读取配置信息 Properties pt=new Properties(); FileReader fr=new FileReader(file);//当然也可采用字节流的方式读取,换成FileInputStream pt.load(fr); String count=pt.getProperty("time"); int value=0; if(count!=null) { value=Integer.parseInt(count); if(value>=time) { throw new RuntimeException("您已使用"+time+"次,请注册!!!"); } } value++; System.out.println("本软件您已使用:"+value+"次!"); pt.setProperty("time", String.valueOf(value));//后者可换成value+"" //接下来IO流保存配置信息 FileWriter fw=new FileWriter(file);//当然也可采用字节流的方式保存,换成FileOutputStream pt.store(fw, "timeproperties"); fr.close(); fw.close(); } }
还没有评论,来说两句吧...