[Java-11] Summary of knowledge about IO stream, Properties collection, and IO tools

main content

  • Introduction to IO streams
  • Classification of IO streams
  • byte output stream
  • byte input stream
  • byte buffer stream
  • Properties set

1 Introduction to IO stream

1.1 Why learn IO stream

  • Store data in variables, arrays, or collections
    • They cannot be permanently stored, because the data is stored in memory
    • As soon as the code finishes running, all data will be lost
  • Use IO streams
    • 1. Write the data to the file to achieve permanent data storage
    • 2. Read the data in the file into the memory (Java program)

1.2 What is an IO stream

  • I stands for input, which is the process of data entering the memory from the hard disk, which is called reading.
  • O means output, which is the process of data from memory to hard disk. call it write
  • IO data transmission can be regarded as a kind of data flow, according to the flow direction, with memory as a reference, read and write operations
    • Simply put: memory is read, memory is written

1.3 Classification of IO streams

  • According to flow direction
    • Input stream: used to read data
    • output stream: used to write data
  • by type
    • byte stream
    • character stream
  • Notice :
    • Byte streams can manipulate arbitrary files
    • Character streams can only operate on plain text files
    • If you can open it with Windows Notepad and understand it, then such a file is a plain text file.

2 byte stream output stream

2.1 Getting Started with Byte Output Streams

  • FileOutputStream class:
    • OutputStreamThere are many subclasses, let's start with the simplest one.
    • java.io.FileOutputStream Class is a file output stream for writing data out to a file
  • Construction method :
    • public FileOutputStream(File file): Creates a file output stream to write to the file represented by the specified File object.
    • public FileOutputStream(String name): Create a file output stream to write to the file with the specified name.
    public class FileOutputStreamConstructor throws IOException {
          
          
        public static void main(String[] args) {
          
          
       	 	// 使用File对象创建流对象
            File file = new File("a.txt");
            FileOutputStream fos = new FileOutputStream(file);
          
            // 使用文件名称创建流对象
            FileOutputStream fos = new FileOutputStream("b.txt");
        }
    }
    
  • A Quick Start for Writing Data to a Byte Output Stream
    • Create a byte output stream object.
    • write data
    • release resources
    package com.bn.outputstream_demo;
    
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    /*
        字节输出流写数据快速入门 :
            1 创建字节输出流对象。
            2 写数据
            3 释放资源
     */
    public class OutputStreamDemo1 {
          
          
        public static void main(String[] args) throws IOException {
          
          
            // 创建字节输出流对象
            // 如果指定的文件不存在 , 会自动创建文件
            // 如果文件存在 , 会把文件中的内容清空
            FileOutputStream fos = new FileOutputStream("day11_demo\\a.txt");
    
            // 写数据
            // 写到文件中就是以字节形式存在的
            // 只是文件帮我们把字节翻译成了对应的字符 , 方便查看
            fos.write(97);
            fos.write(98);
            fos.write(99);
    
            // 释放资源
            // while(true){}
            // 断开流与文件中间的关系
            fos.close();
        }
    }
    

2.2 Method of writing data in byte output stream

  • The method of writing data by byte stream

    • 1 void write(int b) write one byte of data at a time
    • 2 void write(byte[] b) Write one byte array data at a time
    • 3 void write(byte[] b, int off, int len) Write part of data of a byte array at a time
    package com.bn.outputstream_demo;
    
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    /*
        字节流写数据的3种方式
            1 void write​(int b)	一次写一个字节数据
            2 void write​(byte[] b)	一次写一个字节数组数据
            3 void write​(byte[] b, int off, int len)	一次写一个字节数组的部分数据
     */
    public class OutputStreamDemo2 {
        public static void main(String[] args) throws IOException {
            // 创建字节输出流对象
            FileOutputStream fos = new FileOutputStream("day11_demo\\a.txt");
    
            // 写数据
    //        1 void write​(int b)	一次写一个字节数据
            fos.write(97);
            fos.write(98);
            fos.write(99);
    
    //        2 void write​(byte[] b)	一次写一个字节数组数据
            byte[] bys = {65, 66, 67, 68, 69};
            fos.write(bys);
    
    //        3 void write​(byte[] b, int off, int len)	一次写一个字节数组的部分数据
            fos.write(bys, 0, 3);
    
            // 释放资源
            fos.close();
        }
    }
    

2.3 Newline and additional writing of written data

package com.bn.outputstream_demo;

import java.io.FileOutputStream;
import java.io.IOException;

/*
    字节流写数据的换行和追加写入

    1 字节流写数据如何实现换行呢?
        写完数据后,加换行符
        windows : \r\n
        linux : \n
        mac : \r

    2 字节流写数据如何实现追加写入呢?
        通过构造方法 : public FileOutputStream(String name,boolean append)
        创建文件输出流以指定的名称写入文件。如果第二个参数为true ,不会清空文件里面的内容
 */
public class OutputStreamDemo3 {
    public static void main(String[] args) throws IOException {
        // 创建字节输出流对象
        FileOutputStream fos = new FileOutputStream("day11_demo\\a.txt");

        // void write(int b)  一次写一个字节数据
        fos.write(97);
        // 因为字节流无法写入一个字符串 , 把字符串转成字节数组写入
        fos.write("\r\n".getBytes());
        fos.write(98);
        fos.write("\r\n".getBytes());
        fos.write(99);
        fos.write("\r\n".getBytes());

        // 释放资源
        fos.close();
    }
}
package com.bn.outputstream_demo;

import java.io.FileOutputStream;
import java.io.IOException;

/*
    字节流写数据的换行和追加写入

    1 字节流写数据如何实现换行呢?
        写完数据后,加换行符
        windows : \r\n
        linux : \n
        mac : \r

    2 字节流写数据如何实现追加写入呢?
        通过构造方法 : public FileOutputStream​(String name,boolean append)
        创建文件输出流以指定的名称写入文件。如果第二个参数为true ,不会清空文件里面的内容
 */
public class OutputStreamDemo3 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        // 创建字节输出流对象
        // 追加写数据
        // 通过构造方法 : public FileOutputStream​(String name,boolean append) : 追加写数据
        FileOutputStream fos = new FileOutputStream("day11_demo\\a.txt" , true);

        // void write​(int b)	一次写一个字节数据
        fos.write(97);
        // 因为字节流无法写入一个字符串 , 把字符串转成字节数组写入
        fos.write("\r\n".getBytes());
        fos.write(98);
        fos.write("\r\n".getBytes());
        fos.write(99);
        fos.write("\r\n".getBytes());

        // 释放资源
        fos.close();
    }
    // 写完数据换行操作
    private static void method1() throws IOException {
    
    
        // 创建字节输出流对象
        FileOutputStream fos = new FileOutputStream("day11_demo\\a.txt");

        // void write​(int b)	一次写一个字节数据
        fos.write(97);
        // 因为字节流无法写入一个字符串 , 把字符串转成字节数组写入
        fos.write("\r\n".getBytes());
        fos.write(98);
        fos.write("\r\n".getBytes());
        fos.write(99);
        fos.write("\r\n".getBytes());

        // 释放资源
        fos.close();
    }
}

3 byte input stream

3.1 Introduction to byte input stream

  • byte input stream class
    • InputStream class: The top-level class of the byte input stream, an abstract class
      —FileInputStream class: FileInputStream extends InputStream
  • Construction method
    • public FileInputStream(File file) : read data from the path of file type
    • public FileInputStream(String name) : read data from string path
  • step
    • Create an input stream object
    • read data
    • release resources
  • package com.bn.inputstream_demo;
    
    import java.io.FileInputStream;
    import java.io.IOException;
    
    /*
        字节输入流写数据快速入门 : 一次读一个字节
                第一部分 : 字节输入流类
                    InputStream类 : 字节输入流最顶层的类 , 抽象类
                    --- FileInputStream类 : FileInputStream extends InputStream
                第二部分 : 构造方法
                    public FileInputStream(File file) :  从file类型的路径中读取数据
                    public FileInputStream(String name) : 从字符串路径中读取数据
                第三部分 : 字节输入流步骤
                    1 创建输入流对象
                    2 读数据
                    3 释放资源
     */
    public class FileInputStreamDemo1 {
        public static void main(String[] args) throws IOException {
            // 创建字节输入流对象
            // 读取的文件必须存在 , 不存在则报错
            FileInputStream fis = new FileInputStream("day11_demo\\a.txt");
    
            // 读数据 , 从文件中读到一个字节
            // 返回的是一个int类型的字节
            // 如果想看字符, 需要强转
            int by = fis.read();
            System.out.println((char) by);
    
            // 释放资源
            fis.close();
        }
    }
    

3.2 Byte input stream read multiple bytes

package com.bn.inputstream_demo;

import java.io.FileInputStream;
import java.io.IOException;

/*
    字节输入流写数据快速入门 : 读多个字节
            第一部分 : 字节输入流类
                InputStream类 : 字节输入流最顶层的类 , 抽象类
                --- FileInputStream类 : FileInputStream extends InputStream
            第二部分 : 构造方法
                public FileInputStream(File file) :  从file类型的路径中读取数据
                public FileInputStream(String name) : 从字符串路径中读取数据
            第三部分 : 字节输入流步骤
                1 创建输入流对象
                2 读数据
                3 释放资源
 */
public class FileInputStreamDemo2 {
    public static void main(String[] args) throws IOException {
        // 创建字节输入流对象
        // 读取的文件必须存在 , 不存在则报错
        FileInputStream fis = new FileInputStream("day11_demo\\a.txt");

        // 读数据 , 从文件中读到一个字节
        // 返回的是一个int类型的字节
        // 如果想看字符, 需要强转
//        int by = fis.read();
//        System.out.println(by);
//        by = fis.read();
//        System.out.println(by);
//        by = fis.read();
//        System.out.println(by);
//
//        by = fis.read();
//        System.out.println(by);
//        by = fis.read();
//        System.out.println(by);
//        by = fis.read();
//        System.out.println(by);

        // 循环改进
        int by;// 记录每次读到的字节
        while ((by = fis.read()) != -1) {
            System.out.print((char) by);
        }

        // 释放资源
        fis.close();
    }
}

3.3 Copying of pictures

package com.bn.inputstream_demo;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/*
    需求 : 把 "图片路径\xxx.jpg" 复制到当前模块下

    分析:
        复制文件,其实就把文件的内容从一个文件中读取出来(数据源),然后写入到另一个文件中(目的地)
        数据源:
            xxx.jpg  --- 读数据 --- FileInputStream
        目的地:
            模块名称\copy.jpg --- 写数据 --- FileOutputStream

 */
public class FileInputStreamDemo2 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        // 创建字节输入流对象
        FileInputStream fis = new FileInputStream("D:\\liqin.jpg");

        // 创建字节输出流
        FileOutputStream fos = new FileOutputStream("day11_demo\\copy.jpg");

        // 一次读写一个字节
        int by;
        while ((by = fis.read()) != -1) {
    
    
            fos.write(by);
        }

        // 释放资源
        fis.close();
        fos.close();
    }
}

3.4 Exception capture and processing

  • Processing method before JDK7 version: Manually release resources
    package com.itheima.inputstream_demo;
    
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    /*
        需求 : 对上一个赋值图片的代码进行使用捕获方式处理
     */
    public class FileInputStreamDemo4 {
          
          
        public static void main(String[] args) {
          
          
            FileInputStream fis = null ;
            FileOutputStream fos = null;
            try {
          
          
                // 创建字节输入流对象
                fis = new FileInputStream("D:\\liqin.jpg");
    
                // 创建字节输出流
                fos = new FileOutpu	tStream("day11_demo\\copy.jpg");
    
                // 一次读写一个字节
                int by;
                while ((by = fis.read()) != -1) {
          
          
                    fos.write(by);
                }
            } catch (IOException e) {
          
          
                e.printStackTrace();
            } finally {
          
          
                // 释放资源
                if(fis != null){
          
          
                    try {
          
          
                        fis.close();
                    } catch (IOException e) {
          
          
                        e.printStackTrace();
                    }
                }
                // 释放资源
                if(fos != null){
          
          
                    try {
          
          
                        fos.close();
                    } catch (IOException e) {
          
          
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
    
  • JDK7 version optimization processing method: automatically release resources
    • After JDK7 optimization, the try-with-resource statement can be used, which ensures that each resource is automatically closed at the end of the statement.
      Simple understanding: use this statement, resources will be released automatically, no need to write finally code block yourself

    • Format :

      格式 :  
      try (创建流对象语句1 ; 创建流对象语句2 ...) {
              
              
              // 读写数据
          } catch (IOException e) {
              
              
              处理异常的代码...
          }
      
      举例 :
          try ( 
              FileInputStream fis1 = new FileInputStream("day11_demo\\a.txt") ; 
      	    FileInputStream fis2 = new FileInputStream("day11_demo\\b.txt") ) 
          {
              
              
              // 读写数据
          } catch (IOException e) {
              
              
              处理异常的代码...
          }
      
      
  • code practice
    package com.itheima.inputstream_demo;
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    /*
        JDK7版本优化处理方式
    
        需求 : 对上一个赋值图片的代码进行使用捕获方式处理
     */
    public class FileInputStreamDemo5 {
          
          
        public static void main(String[] args) {
          
          
            try (
                    // 创建字节输入流对象
                    FileInputStream fis = new FileInputStream("D:\\liqin.jpg");
                    // 创建字节输出流
                    FileOutputStream fos = new FileOutputStream("day11_demo\\copy.jpg")
            ) {
          
          
                // 一次读写一个字节
                int by;
                while ((by = fis.read()) != -1) {
          
          
                    fos.write(by);
                }
                // 释放资源 , 发现已经灰色 , 提示多余的代码 , 所以使用 try-with-resource 方式会自动关流
                // fis.close();
                // fos.close();
            } catch (IOException e) {
          
          
                e.printStackTrace();
            }
        }
    }
    

3.4 Byte input stream reads one byte array at a time

  • FileInputStream class:

    • public int read(byte[] b) : read up to b.length bytes of data from the input stream, and return the number of actually read data
    package com.bn.inputstream_demo;
    
    
    import javax.sound.midi.Soundbank;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    /*
       FileInputStream类 :
            public int read​(byte[] b):
            1 从输入流读取最多b.length个字节的数据
            2 返回的是真实读到的数据个数
     */
    public class FileInputStreamDemo6 {
          
          
        public static void main(String[] args) throws IOException {
          
          
            // 创建字节输入流对象
            FileInputStream fis = new FileInputStream("day11_demo\\a.txt");
    
    //        public int read​(byte[] b):
    //        1 从输入流读取最多b.length个字节的数据
    //        2 返回的是真实读到的数据个数
    
            byte[] bys = new byte[3];
    
    //        int len = fis.read(bys);
    //        System.out.println(len);// 3
    //        System.out.println(new String(bys));// abc
    //
    //        len = fis.read(bys);
    //        System.out.println(len);// 2
    //        System.out.println(new String(bys));// efc
    
            System.out.println("==========代码改进===============");
    
    //        int len = fis.read(bys);
    //        System.out.println(len);// 3
    //        System.out.println(new String(bys, 0, len));// abc
    //
    //        len = fis.read(bys);
    //        System.out.println(len);// 2
    //        System.out.println(new String(bys, 0, len));// ef
    
            System.out.println("==========代码改进===============");
    
            int len;
            while ((len = fis.read(bys)) != -1) {
          
          
                System.out.print(new String(bys , 0 , len));
            }
    
            fis.close();
        }
    }
    
    
  • Improve the code for copying pictures by reading and writing a byte array at a time

    package com.bn.inputstream_demo;
    
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    /*
        需求 : 对复制图片的代码进行使用一次读写一个字节数组的方式进行改进
    
        FileInputStream类 :
            public int read​(byte[] b):
            1 从输入流读取最多b.length个字节的数据
            2 返回的是真实读到的数据个数
     */
    public class FileInputStreamDemo7 {
          
          
        public static void main(String[] args) throws IOException {
          
          
            // 创建字节输入流对象
            FileInputStream fis = new FileInputStream("D:\\liqin.jpg");
            // 创建字节输出流
            FileOutputStream fos = new FileOutputStream("day11_demo\\copy.jpg");
    
            byte[] bys = new byte[1024];
            int len;// 每次真实读到数据的个数
            int by;
            while ((len = fis.read(bys)) != -1) {
          
          
                fos.write(bys, 0, len);
            }
    
            // 释放资源
            fis.close();
            fos.close();
        }
    }
    
    

4 byte buffer stream

4.1 Overview of Byte Buffer Streams

  • byte buffered stream:

    • ​ BufferOutputStream: Buffered output stream
    • ​ BufferedInputStream: Buffered input stream
  • Construction method:

    • ​ Byte buffer output stream: BufferedOutputStream(OutputStream out)
    • ​ Byte buffer input stream: BufferedInputStream(InputStream in)
  • Why does the construction method need a byte stream instead of a specific file or path?

    • ​ The byte buffer stream only provides a buffer and does not have read and write functions, and the real read and write data has to rely on the basic byte stream object for operation

4.2 Case of byte buffer stream

package com.bn.bufferedstream_demo;

import java.io.*;

/*
    字节缓冲流:
        BufferOutputStream:缓冲输出流
        BufferedInputStream:缓冲输入流

    构造方法:
        字节缓冲输出流:BufferedOutputStream​(OutputStream out)
        字节缓冲输入流:BufferedInputStream​(InputStream in)

    为什么构造方法需要的是字节流,而不是具体的文件或者路径呢?
        字节缓冲流仅仅提供缓冲区,不具备读写功能 , 而真正的读写数据还得依靠基本的字节流对象进行操作

    需求 : 使用缓冲流进行复制文件

 */
public class BufferedStreamDemo1 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        // 创建高效的字节输入流对象
        // 在底层会创建一个长度为8192的数组
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\liqin.jpg"));
        // 创建高效的字节输出流
        // 在底层会创建一个长度为8192的数组
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("day11_demo\\copy.jpg"));

        // 使用高效流 , 一次读写一个字节
        int by;
        while ((by = bis.read()) != -1) {
    
    
            bos.write(by);
        }

//        byte[] bys = new byte[1024];
//        int len;// 每次真实读到数据的个数
//        while ((len = bis.read(bys)) != -1) {
    
    
//            bos.write(bys, 0, len);
//        }

        // 释放资源
        // 在底层会把基本的流进行关闭
        bis.close();
        bos.close();
    }
}

  • Four ways to copy video files
package com.bn.bufferedstream_demo;

import java.awt.image.DataBufferDouble;
import java.io.*;

/*
    需求:把“xxx.avi”复制到模块目录下的“copy.avi” , 使用四种复制文件的方式 , 打印所花费的时间

    四种方式:
        1 基本的字节流一次读写一个字节          : 花费的时间为:196662毫秒
        2 基本的字节流一次读写一个字节数组      : 花费的时间为:383毫秒
        3 缓冲流一次读写一个字节                : 花费的时间为:365毫秒
        4 缓冲流一次读写一个字节数组            : 花费的时间为:108毫秒

    分析 :
        数据源 : "D:\a.wmv"
        目的地 : "day11_demo\copy.wmv"
 */
public class BufferedStreamDemo2 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        long startTime = System.currentTimeMillis();

        // method1();
        // method2();
        // method3();
        method4();

        long endTime = System.currentTimeMillis();
        System.out.println("花费的时间为:" + (endTime - startTime) + "毫秒");
    }

    // 4 缓冲流一次读写一个字节数组
    private static void method4() throws IOException {
    
    
        // 创建高效的字节输入流
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\a.wmv"));
        // 创建高效的字节输出流
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("day11_demo\\copy.wmv"));

        // 一次读写一个字节数组
        byte[] bys = new byte[1024];
        int len;// 每次真实读到数据的个数
        while ((len = bis.read(bys)) != -1) {
    
    
            bos.write(bys, 0, len);
        }

        // 释放资源
        bis.close();
        bos.close();
    }

    //  3 缓冲流一次读写一个字节
    private static void method3() throws IOException {
    
    
        // 创建高效的字节输入流
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\a.wmv"));
        // 创建高效的字节输出流
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("day11_demo\\copy.wmv"));

        // 一次读写一个字节
        int by;
        while ((by = bis.read()) != -1) {
    
    
            bos.write(by);
        }


        // 释放资源
        bis.close();
        bos.close();
    }

    // 2 基本的字节流一次读写一个字节数组
    private static void method2() throws IOException {
    
    
        // 创建基本的字节输入流对象
        FileInputStream fis = new FileInputStream("D:\\a.wmv");
        // 创建基本的字节输出流对象
        FileOutputStream fos = new FileOutputStream("day11_demo\\copy.wmv");

        // 一次读写一个字节数组
        byte[] bys = new byte[1024];
        int len;// 每次真实读到数据的个数
        while ((len = fis.read(bys)) != -1) {
    
    
            fos.write(bys, 0, len);
        }

        // 释放资源
        fis.close();
        fos.close();
    }

    // 1 基本的字节流一次读写一个字节
    private static void method1() throws IOException {
    
    
        // 创建基本的字节输入流对象
        FileInputStream fis = new FileInputStream("D:\\a.wmv");
        // 创建基本的字节输出流对象
        FileOutputStream fos = new FileOutputStream("day11_demo\\copy.wmv");

        // 一次读写一个字节
        int by;
        while ((by = fis.read()) != -1) {
    
    
            fos.write(by);
        }

        // 释放资源
        fis.close();
        fos.close();
    }
}

5.1 Overview of the Properties collection

  • properties is a collection class of Map system

    • public class Properties extends Hashtable <Object,Object>
  • Why study Properties in the IO stream section

    • There are methods related to IO in Properties
  • Use as a double-column collection

    • There is no need to add generics, only strings are stored in the work
    package com.itheima.properties_demo;
    
    import java.util.Map;
    import java.util.Properties;
    import java.util.Set;
    
    /*
        1 properties是一个Map体系的集合类
            - `public class Properties extends Hashtable <Object,Object>`
        2 为什么在IO流部分学习Properties
            - Properties中有跟IO相关的方法
        3 当做双列集合使用
            - 不需要加泛型 , 工作中只存字符串
     */
    public class PropertiesDemo1 {
          
          
        public static void main(String[] args) {
          
          
            // 创建集合对象
            Properties properties = new Properties();
    
            // 添加元素
            properties.put("it001" , "张三");
            properties.put("it002" , "李四");
            properties.put("it003" , "王五");
    
            // 遍历集合 : 键找值
            Set<Object> set = properties.keySet();
            for (Object key : set) {
          
          
                System.out.println(key + "---" + properties.get(key));
            }
    
            System.out.println("========================");
            
            // 遍历集合 : 获取对对象集合 , 获取键和值
            Set<Map.Entry<Object, Object>> set2 = properties.entrySet();
            for (Map.Entry<Object, Object> entry : set2) {
          
          
                Object key = entry.getKey();
                Object value = entry.getValue();
                System.out.println(key + "---" + value);
            }
        }
    }
    

5.2 Properties as a unique method of collection

  • Object setProperty(String key, String value) Set the key and value of the collection, both of which are of String type, equivalent to the put method
  • String getProperty(String key) Use the key specified in this property list to search for properties, equivalent to the get method
  • Set stringPropertyNames() returns an unmodifiable key set from the property list, where the keys and their corresponding values ​​are strings, equivalent to the keySet method
package com.itheima.properties_demo;

import java.util.Properties;
import java.util.Set;

/*
    Properties作为集合的特有方法
        Object setProperty(String key, String value)	设置集合的键和值,都是String类型,相当于put方法
        String getProperty(String key)	使用此属性列表中指定的键搜索属性 , 相当于get方法
        Set<String> stringPropertyNames​()	从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串 , 相当于keySet方法
 */
public class PropertiesDemo2 {
    
    

    public static void main(String[] args) {
    
    
        // 创建集合对象
        Properties properties = new Properties();

        // 添加元素
        properties.setProperty("it001", "张三");
        properties.setProperty("it002", "李四");
        properties.setProperty("it003", "王五");

        // 遍历集合 : 键找值
        Set<String> set = properties.stringPropertyNames();
        for (String key : set) {
    
    
            System.out.println(key + "---" + properties.getProperty(key));
        }
    }
}

5.3 Methods related to IO in properties

  • void load(InputStream inStream) reads the key-value pairs in the file into the collection in the form of byte stream
  • void load(Reader reader) reads the key-value pairs in the file into the collection in the form of character stream
  • void store(OutputStream out, String comments) Write the key-value pairs in the collection into the file in the form of byte stream, the second parameter is the comment
  • void store(Writer writer, String comments) Write the key-value pairs in the collection into the file in the form of a character stream, and the second parameter is a comment
package com.bn.properties_demo;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/*
   Properties和IO流结合的方法
        void load​(InputStream inStream)	以字节流形式 , 把文件中的键值对, 读取到集合中
        //void load​(Reader reader)	以字符流形式 , 把文件中的键值对, 读取到集合中
        void store​(OutputStream out, String comments)	把集合中的键值对,以字节流形式写入文件中 , 参数二为注释
        //void store​(Writer writer, String comments)	把集合中的键值对,以字符流形式写入文件中 , 参数二为注释
 */
public class PropertiesDemo3 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        // 创建Properties集合对象
        Properties properties = new Properties();

        /w/ void load​(InputStream inStream)	以字节流形式 , 把文件中的键值对, 读取到集合中
        properties.load(new FileInputStream("day11_demo\\prop.properties"));

        // 打印集合中的数据
        System.out.println(properties);
    }
}

package com.itheima.properties_demo;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/*
   Properties和IO流结合的方法
        void load​(InputStream inStream)	以字节流形式 , 把文件中的键值对, 读取到集合中
        //void load​(Reader reader)	以字符流形式 , 把文件中的键值对, 读取到集合中
        void store​(OutputStream out, String comments)	把集合中的键值对,以字节流形式写入文件中 , 参数二为注释
        //void store​(Writer writer, String comments)	把集合中的键值对,以字符流形式写入文件中 , 参数二为注释
 */
public class PropertiesDemo3 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        Properties properties = new Properties();
        properties.setProperty("zhangsan" , "23");
        properties.setProperty("lisi" , "24");
        properties.setProperty("wangwu" , "25");
        properties.store(new FileOutputStream("day11_demo\\prop2.properties") , "userMessage");
    }

    private static void method1() throws IOException {
    
    
        // 创建Properties集合对象
        Properties properties = new Properties();

        // void load​(InputStream inStream)	以字节流形式 , 把文件中的键值对, 读取到集合中
        properties.load(new FileInputStream("day11_demo\\prop.properties"));

        // 打印集合中的数据
        System.out.println(properties);
    }
}

6 ResourceBundle load property file

learning target

  • Be able to skillfully use the ResourceBundle tool class to quickly read the value of the property file

Content explanation

【1】API Introduction

java.util.ResourceBundleIt is an abstract class, and we can use its subclass PropertyResourceBundle to read configuration files ending in .properties.

Obtain the object directly through the static method:
static ResourceBundle getBundle(String baseName) 可以根据名字直接获取默认语言环境下的属性资源。
参数注意: baseName 
  	1.属性集名称不含扩展名。
    2.属性集文件是在src目录中的
  
比如:src中存在一个文件 user.properties
ResourceBundle bundle = ResourceBundle.getBundle("user");

Common methods in ResourceBundle:

 String getString(String key) : 通过键,获取对应的值

[2] Code practice

Through the ResourceBundle tool class

Put a property file in the src directory and use ResourceBundle to get the key-value pair data

package com.itheima.resourcebundle_demo;

import java.util.ResourceBundle;

/*
    1   java.util.ResourceBundle : 它是一个抽象类
        我们可以使用它的子类PropertyResourceBundle来读取以.properties结尾的配置文件

    2   static ResourceBundle getBundle(String baseName) 可以根据名字直接获取默认语言环境下的属性资源。
        参数注意: baseName
            1.属性集名称不含扩展名。
            2.属性集文件是在src目录中的
        比如:src中存在一个文件 user.properties
        ResourceBundle bundle = ResourceBundle.getBundle("user");

    3 ResourceBundle中常用方法:
         String getString(String key) : 通过键,获取对应的值

    优点 : 快速读取属性文件的值

     需求 :
        通过ResourceBundle工具类
        将一个属性文件 放到src目录中,使用ResourceBundle去获取键值对数据
 */
public class ResourceBundleDemo {
    
    
    public static void main(String[] args) {
    
    
        // public static final ResourceBundle getBundle(String baseName)
        // baseName : properties文件的名字 , 注意 : 扩展名不需要加上 , properties必须在src的根目录下
        ResourceBundle resourceBundle = ResourceBundle.getBundle("user");

        // String getString(String key) : 通过键,获取对应的值
        String value1 = resourceBundle.getString("username");
        String value2 = resourceBundle.getString("password");
        System.out.println(value1);
        System.out.println(value2);
    }
}

Content summary

  1. If you want to use ResourceBundle to load property files, where should the property files be placed?

    src的根目录
    
  2. Please describe the general steps of using ResourceBundle to obtain attribute values?

    1 获取ResourceBundle对象
    2 通过ResourceBundle类中的getString(key) : 根据键找值
    

Guess you like

Origin blog.csdn.net/wanghaoyingand/article/details/130976599