Properties学习

来源:互联网 发布:mysql 全球地区数据表 编辑:程序博客网 时间:2024/06/10 08:41

package cn.zen.io.properties;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.IOException;import java.util.Properties;import java.util.Set;import org.junit.Test;public class PropertiesEx {@Testpublic void method_1() {Properties prop = new Properties();prop.setProperty("ZhangSan", "100");prop.setProperty("LiSi", "120");prop.setProperty("WangWu", "99");// System.out.println(prop.getProperty("LiSi"));Set<String> nameSet = prop.stringPropertyNames();for (String name : nameSet) {System.out.println(name + "->" + prop.getProperty(name));}}/** * 将info.ini文件中键值数据存到Properties集合中进行操作 步骤: 1:一个IO流和文件关联info.ini文件关联 * 2:读取一行数据,根据=进行数据切割 3:左边为键,右边为值 存到Properties集合中去 */@Testpublic void method_2() throws IOException {// 由于源是纯文本文件 所以用FileReaderFile initFile = new File("D:\\StudyIo", "info.ini");if (!initFile.exists())System.out.println("该文件不存在!");BufferedReader bufr = new BufferedReader(new FileReader(initFile));Properties prop = new Properties();String buf = null;while ((buf = bufr.readLine()) != null) {// System.out.println(buf);String[] strArr = buf.split("=");// System.out.println(strArr[0]+"->"+strArr[1]);prop.setProperty(strArr[0], strArr[1]);}System.out.println(prop);}@Testpublic void method_3() throws FileNotFoundException, IOException {Properties prop = new Properties();File initFile = new File("D:\\StudyIo", "info.ini");if (!initFile.exists())System.out.println("该文件不存在!");FileInputStream fis = new FileInputStream(initFile);prop.load(fis);prop.setProperty("color", "bule");// System.out.println(prop);// prop.list(System.out);FileOutputStream fos = new FileOutputStream(initFile);prop.store(fos, "color change red to bule");fos.close();fis.close();}}
—————————————————————————————————————————————————————————————————————————————

package cn.zen.io.properties;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.Properties;public class ImitateRegistTip {public static void main(String[] args) throws IOException {Properties prop = new Properties();File initFile = new File("D:\\StudyIo", "info.property");if (!(initFile.exists())) {if (!(initFile.createNewFile())) {System.out.println("创建" + initFile.getName() + "失败!");return;}}FileInputStream fis = new FileInputStream(initFile);prop.load(fis);int cnt = 0;String cntVal = prop.getProperty("accessCnt");if (cntVal != null) {cnt = Integer.parseInt(cntVal);if (cnt >= 3) {System.out.println("试用次数已过,如需再次使用请注册激活!");}}cnt++;prop.setProperty("accessCnt", cnt + "");FileOutputStream fos = new FileOutputStream(initFile);String strMsg = "this is " + cnt + " times access! change accessCnt from "+ (cnt - 1) + " to " + cnt;prop.store(fos, strMsg);fos.close();fis.close();}}




原创粉丝点击