zoukankan      html  css  js  c++  java
  • Java学习笔记41(Properties类)

    Properties可以做到集合的数据持久存储

    它是map接口的一个实现类,可以使用map类的方法,

    不过存在区别:它没有泛型,规定键类型为字符串

    这个集合在以后的开发中会经常用到,比如连接数据库等

    这里简单介绍下基本用法,详细用法在后面介绍

    存储获取键值对:

    package demo;
    
    import java.util.Properties;
    import java.util.Set;
    
    public class PropertiesDemo {
        public static void main(String[] args) {
            function();
        }
        
        public static void function(){
            Properties pro1 = new Properties();
            pro1.setProperty("a", "1");
            pro1.setProperty("b", "2");
            pro1.setProperty("c", "3");
            System.out.println(pro1);
            
            String value = pro1.getProperty("c");
            System.out.println(value);
            
            Set<String> set = pro1.stringPropertyNames();
            for(String key:set){
                System.out.println(key+"="+pro1.getProperty(key));
            }
            
        }
    }

    集合特有方法:

    load方法:

    把文件中的键值对加载到集合中

    新建一个文本文件,后缀修改为.properties,写入键值对

    package demo;
    
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Properties;
    
    public class PropertiesDemo {
        public static void main(String[] args) throws IOException {
            function();
        }
        
        public static void function() throws IOException{
            Properties pro1 = new Properties();
            FileReader fr1 = new FileReader("d:\pro.properties");
            
            pro1.load(fr1);
            fr1.close();
            System.out.println(pro1);
        }
    }

    store方法:

    写入键值对

    package demo;
    
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Properties;
    
    public class PropertiesDemo {
        public static void main(String[] args) throws IOException {
            function();
        }
        
        public static void function() throws IOException{
            Properties pro1 = new Properties();
            pro1.setProperty("name", "zhangsan");
            pro1.setProperty("age", "18");
            pro1.setProperty("email", "123456@qq.com");
            FileWriter fWriter = new FileWriter("d:\a.properties");
            pro1.store(fWriter, "the reason");//第二个参数经常省略
            fWriter.close();
        }
    }
  • 相关阅读:
    HTML学习心得
    VS相关
    安全算法
    第三方库的编译
    C++编译问题
    GCC编译
    linux系统·用户管理
    批处理遍历并计算子文件夹下的文件数目
    [Tianchi] Repeat Buyers Prediction-Challenge the Baseline -- version 0
    win10安装cuda
  • 原文地址:https://www.cnblogs.com/xuyiqing/p/8301653.html
Copyright © 2011-2022 走看看