Java-Day-27( Properties 类 + 章节练习 )

发布时间 2023-06-05 23:38:18作者: 朱呀朱~

Java-Day-27

Properties 类

  • 程序读取 xx.properties 配置文件,修改的话就通过配置文件将信息写入到程序 ( 非写死在程序中,灵活性差,编译代价大 )

  • 传统方法:

    public class Test {
        public static void main(String[] args) throws IOException { // 传统方法
    //        读取db.properties文件,并得到信息
            BufferedReader bufferedReader = new BufferedReader(new FileReader("src\\main\\resources\\db.properties"));
            String line = "";
            while ((line = bufferedReader.readLine()) != null) { // 循环读取
    //            直接输出文件内容
    //            System.out.println(line);
    
                String[] split = line.split("="); // 一次循环,分割一行,每行都"="分割
    //            键值对形式取出
    //            System.out.println(split[0] + "值为:" + split[1]);
    
    //            若是想专门取出某值
                if ("user".equals(split[0])) {
                    System.out.println(split[0] + "值是:" + split[1]);
                }
            }
            bufferedReader.close();
        }
    }
    

基本介绍

  • 专门用于读写配置文件的集合类

    • 配置文件格式:

      键=值

      键=值

  • 注意:键值对不需要有空格,值不需要用引号引起来。默认类型是 String

常用方法

  • load:加载配置文件的键值对到 Properties 对象
  • list:将数据显示到指定设备
  • getProperty(key):根据键获取值
  • setProperty(key, value):设置键值对到 Properties 对象
  • store:将 Properties 中的键值对存储到配置文件 ( 如果文件已存在,则覆盖 ),在 idea 中,保存信息到配置文件,如果含有中文,会存储为其 unicode 码

unicode 查询

public class Test {
    public static void main(String[] args) throws IOException {
//        使用 Properties 类来读取 mysql.properties 文件

//        1. 创建 Properties 对象
        Properties properties = new Properties();
//        2. 加载指定配置文件
        properties.load(new FileReader("src\\main\\resources\\db.properties"));
//        3. 把 k-v 显示到控制台(标准输出)
        properties.list(System.out);
//        4. 根据 key 获取对应的值
        String user = properties.getProperty("user");
        String pwd = properties.getProperty("pwd");
        System.out.println("用户名是:" + user + ", 密码是:" + pwd);
    }
}

练习

  • 使用 Properties 类完成对 mysql.properties 的读取

    • 如上述常用方法里的代码
  • 使用 Properties 类添加 key-val 到新文件 mysql1.properties 中

    public class Test {
        public static void main(String[] args) throws IOException {
    //        使用Properties 类创建配置文件.修改配置文件内容
    
            Properties properties = new Properties();
    //        之前没有此k-v,那就是创建
           properties.setProperty("charset", "utf8");
            properties.setProperty("user", "猪呀"); // 保存"猪呀"的unicode码值
            properties.setProperty("pwd", "abc111");
    
    //        将 k-v 存储文件中即可(流或者字节流的方式)
    //        comments:注释, null就算没有注释,否则会在生成文件时,在第一行多一条:"#注释"
            properties.store(new FileOutputStream("src\\main\\resources\\mysql1.properties"), null);
            System.out.println("保存配置文件成功~");
        }
    }
    
    • mysql1.properties 中

      #Sat Jun 03 22:21:58 CST 2023
      user=\u732A\u5440
      pwd=abc111
      charset=utf8
      
  • 使用 Properties 类完成对 mysql1.properties 的读取,并修改某个 key-val

    • 其他代码都同上述创建时候的代码操作

      //        如果该文件有key,就是修改(没有就是创建)
              properties.setProperty("charset", "utf8");
              properties.setProperty("user", "哇哈哈哈"); // 保存"猪呀"的unicode码值
              properties.setProperty("pwd", "123456");
      
    • 源码

      /*
          Properties 父类是 Hashtable, 底层就是Hashtable核心方法
          public synchronized V put(K key, V value) {
              if (value == null) {    // null的话就是空指针错误
                  throw new NullPointerException();
              }
      
              // Makes sure the key is not already in the hashtable.
              Entry<?,?> tab[] = table;
              int hash = key.hashCode();  // 已存在就是替换
              int index = (hash & 0x7FFFFFFF) % tab.length;
              @SuppressWarnings("unchecked")
              Entry<K,V> entry = (Entry<K,V>)tab[index];
              for(; entry != null ; entry = entry.next) {
                  if ((entry.hash == hash) && entry.key.equals(key)) {
                      V old = entry.value;
                      entry.value = value;  // 替换
                      return old;
                  }
              }
      
              addEntry(hash, key, value, index);  // 不存在,新的key,就是添加新的
              return null;
          }
      */
      

本章作业

  • 作业一要求:

    • 判断 e 盘下是否有文件夹 mytemp,如果没有就创建 mytemp

    • 在 e:\\mytemp 目录下,创建文件 hello.txt

    • 如果 hello.txt 已经存在,提示该文件已经存在,就不要再重复创建了

    • 若是新创建的 hello.txt 文件中,就直接写入 hello, world~

      public class Test {
          public static void main(String[] args) throws IOException {
              String directoryPath = "e:\\mytemp";
              File file = new File(directoryPath);
              if (! file.exists()) {
                  if (file.mkdirs()) {
                      System.out.println(directoryPath + " 下创建成功");
                  } else {
                      System.out.println(directoryPath + " 下创建失败了");
                  }
              }
              String filePath = directoryPath + "\\hello.txt"; // 目录 + 文件:完整路径
              file = new File(filePath);
              if (! file.exists()) {
      //            创建文件
                  if (file.createNewFile()) {
                      System.out.println(filePath + " 文件创建成功");
      //                如果文件存在,就要用BufferedWriter字符输入流写入内容
      //                处理流(节点流)
                      BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
                      bufferedWriter.write("hello, world~");
                      bufferedWriter.close();
                  } else {
                      System.out.println(filePath + " 创建失败了");
                  }
              } else {
                  System.out.println(filePath + " 已经存在,无需再建");
              }
          }
      }
      
  • 作业二要求:

    • 使用 BufferedReader 读取一个文本文件,为每行加上行号,再连同内容一并输出到屏幕上
    public class Test {
        public static void main(String[] args) throws IOException {
            String filePath = "e:\\mytemp\\hello.txt";
    //        String reFilePath = "e:\\mytemp\\re_hello.txt";
    //        String charset = "gbk";
            BufferedReader br = null;
            String line = "";
            int lineNum = 0;
            try {
                br = new BufferedReader(new FileReader(filePath));
    //            为防止出现编码规则不同导致汉字识别不符,就将FileInputStream转成InputStreamReader再转成BufferedReader
    //            br = new BufferedReader(new InputStreamReader(new FileInputStream(reFilePath), charset));
                while ((line = br.readLine()) != null) {
                    System.out.println("第" + ++lineNum + "行:" + line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (br != null) {
                        br.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
  • 作业三要求:

    • 要编写一个 dog.properties

      dogName=zyz

      age=5

      color=red

    • 编写 Dog 类 ( name, age, color ) 创建一个 dog 对象,读取 dog.properties 用相应的内容完成属性初始化,并输出

    • 将创建的 Dog 对象,序列化到文件 dog.dat 文件

    • 再反序列化在控制台显示

      public class Test_java {
          public static void main(String[] args) throws IOException {
      //        编写
              String fileName = "src\\main\\resources\\dog.properties";
              Properties properties = new Properties();
              properties.load(new FileReader(fileName));
              properties.list(System.out);
      
      //        用一个对象读取配置信息并存储
      //        Object dogName = properties.get("dogName");
      //        返回值是Object类型,但要求取到字符串信息
              String dogName = properties.get("dogName") + ""; // Object—>String:后面加一个空的""即可 (或重新再new)
              int age = Integer.parseInt(properties.get("age") + ""); // Object—>int(通过String)
              String color = properties.get("color") + ""; // 同样加一个空串
              Dog dog = new Dog(dogName, age, color);
              System.out.println("===dog对象信息===");
              System.out.println(dog);
      
      //        序列化到文件dog.dat(注意,一个对象想被序列化,就得实现Serializable接口)
              String serFilePath = "e:\\dog.dat";
              ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(serFilePath));
              oos.writeObject(dog);
              oos.close();
              System.out.println("dog对象序列化完成");
          }
          
      //        再编写一个方法,反序列化dog
          @Test
          public void m1() throws Exception {
              String serFilePath = "e:\\dog.dat";
              ObjectInputStream ois = new ObjectInputStream(new FileInputStream(serFilePath));
              Dog dog = (Dog) ois.readObject();
              System.out.println("===反序列化后dog对象信息===");
              System.out.println(dog);
              ois.close();
          }
      
      }
      
      class Dog implements Serializable{
          private String dogName;
          private int age;
          private String color;
      
          public Dog(String dogName, int age, String color) {
              this.dogName = dogName;
              this.age = age;
              this.color = color;
          }
          
      //    getter and setter 
      //    ......
      
          @Override
          public String toString() {
              return "Dog{" +
                      "dogName='" + dogName + '\'' +
                      ", age=" + age +
                      ", color='" + color + '\'' +
                      '}';
          }
      }
      
    • 使用@Test注解时报错

      • 报错修改后显示@org.junit.jupiter.api.Test:所在类名也叫Test,
      • 没导jar包 ( 依赖 ):junit
      • 依赖版本低