How to understand the IO stream in Java - streamlining

Table of contents

introduction

buffered stream 

byte buffer stream 

character buffer stream 

transform stream 

character input conversion stream 

character output conversion stream 

Serialize and deserialize 

object serialization 

Object deserialization 

print stream 

Properties


 

introduction

Through the previous simple study, we have been able to have a general understanding of the operation of the file, but we can clearly feel that there will still be some inconveniences when performing other operations, so today we will learn another four IO streams To help us operate on files, these four streams are buffering stream , conversion stream , serialization, and print stream . Well, without further ado, let me start today's study!

 

 

buffered stream 

  • Buffered streaming is also known as efficient streaming, or advanced streaming. The previously learned byte stream can also be called a raw stream.
  • Function: The buffer stream has its own buffer, which can improve the performance of reading data from the original byte stream and character stream.
  • Image example : If we imagine the input and output operations of the file as the process of transporting water, at the beginning, the water (data) is directly connected to the water pipe for transportation, and the difference between the buffer flow is that the water does not need to be connected to the water pipe. , it only needs to be docked with the water tank in front of the water pipe, which can improve the efficiency of transportation.
  • There are two types of buffer streams, one is byte buffer stream and the other is character buffer stream. They are BufferedInputStream (byte buffered input stream) , BufferedOuputStream (byte buffered output stream) , BufferedReader (character buffered input stream) , BufferedWriter (character buffered output stream). 

byte buffer stream 

  • Byte buffered input stream : BufferedInputStream, improves the performance of reading data from byte input stream, and the read and write functions have not changed
  • Byte buffered output stream : BufferedOutputStream, improves the performance of reading data from byte output stream, and there is no change in read and write functions
Constructor illustrate

public BufferedInputStream(InputStream is)

The low-level byte input stream can be wrapped into a high-level byte-buffered input stream pipeline, thereby improving the performance of reading data from the byte input stream
public BufferedOutputStream(OutputStream os) The low-level byte output stream can be wrapped into a high-level byte-buffered output stream pipeline, thereby improving the performance of writing data
InputStream is = new FileInputStream("File//data.txt");
InputStream bis = new BufferedInputStream(is);
OutputStream os = new FileOutputStream("File//data01.txt");
OutputStream bos = new BufferedOutputStream(os);
int len;
byte []buffer = new byte[1024];
while ((len = bis.read(buffer))!=-1){
bos.write(buffer,0,len);
bos.flush();

Copies the contents of one file into another through a byte buffer stream.

 

character buffer stream 

Character buffered input stream : BufferedReader, which improves the performance of character input stream reading data, in addition to the function of reading data by line

Constructor illustrate
public BufferedReader(Reader r) The low-level character input stream can be wrapped into a high-level buffered character input stream pipeline, thereby improving the performance of reading data from the character input stream
method illustrate
public String readLine() Read a row of data and return, if the reading is not completed, there is no row to read and return null
        Reader r = new FileReader("File//data.txt");
        BufferedReader br = new BufferedReader(r);//由于是子类独有的功能,所有不能使用多态创建
        String s;
        byte []buffer = new byte[1024];
        while ((s = br.readLine())!=null){
            System.out.println(s);
        }
//正常情况下会将文件中的数据依次输出;
        Reader r = new FileReader("File//data.txt");
        BufferedReader br = new BufferedReader(r);
        br.readLine();
        br.readLine();
//若文件中的数据不足两行:
//kdirvingJamesJame
//null

Character buffered output stream : BufferedWriter, which improves the performance of character output stream writing data, in addition to the newline function 

Constructor illustrate
public BufferedWriter(Writer w) The low-level character output stream can be packaged into a high-level buffered character output stream pipeline, thereby improving the performance of writing data to the character output stream
method illustrate
public void newLine() perform action
        Writer w = new FileWriter("File//data.txt",true);
        BufferedWriter bw = new BufferedWriter(w);//由于是子类独有的功能,所有不能使用多态创建
        bw.write("石原里美");
        bw.newLine();
        bw.write("工藤静香");
        bw.newLine();
        bw.flush();

It should be noted that if you want to append the file when writing the file, you need to set true to the Writer object, not the BufferedWriter object.

 

transform stream 

Before learning about conversion streams, what we should understand is if the code encoding and the file encoding are inconsistent. Using the character stream to read directly will cause garbled characters, so we need the code encoding and file encoding to be consistent to ensure that there will be no garbled characters, and the appearance of the conversion stream is to avoid this kind of thing from happening. 

 

character input conversion stream 

The first is to provide a simple idea for the problem of garbled characters:

1. Use character input to convert streams;

2. The original byte stream of the file (different encoding) can be extracted, and there will be no problem with the original byte;

3. Convert the byte stream to the character input stream with the specified encoding, so that the characters in the character input stream will not be garbled.

Character input conversion stream: InputStreamReader, which can convert the original byte stream into a character input stream according to the specified encoding

Constructor illustrate
public InputStreamReader(InputStream is) The original byte stream can be converted into a character input stream according to the default encoding of the code. hardly ever
public InputStreamReader(InputStream is,String charset) The original byte stream can be converted into a character input stream according to the specified encoding, so that the characters in the character stream are not garbled

        InputStream is = new FileInputStream("File//data.txt");
        InputStreamReader isr = new InputStreamReader(is);
        InputStreamReader isr = new InputStreamReader(is,"GBK");

In the above code, it is known that the encoding format of the data.txt file is set to GBK, and the code encoding is utf-8, so it is necessary to convert the stream to make the encoding consistent. One constructor defaults to utf-8, which is obviously not acceptable. The second is to specify the encoding, convert the original byte input stream into a character input stream, and read it in the shape of GBK.

character output conversion stream 

Character output conversion stream: OutputStreamWriter, which can convert the byte output stream into a character output stream according to the specified encoding

Constructor illustrate
public OutputStreamWriter(OutputStream os) The original byte output stream can be converted into a character output stream according to the default encoding of the code, almost no use
public OutputStreamWriter(OutputStream os,String charset) It can convert the original byte output stream into a character output stream according to the specified encoding

First of all, we should know what real-world things the character output conversion stream is for At this time, we need to pass a file encoded as GBK.

        OutputStream os = new FileOutputStream("File//data.txt");
        Writer osw = new OutputStreamWriter(os);
        Writer osw = new OutputStreamWriter(os,"GBK");

In the above code, the first is the default utf-8, so it is almost useless, and the second is to specify the encoding file format required by the customer.

 

Serialize and deserialize 

object serialization 

  • Object byte output stream , ObjectOutputStream
  • Function: Based on memory, store objects in memory to disk files, which is called object serialization
Constructor illustrate
public ObjectOutputStream(OutputStream os) Wrap the low-level byte output stream into a high-level object byte output stream

 The first is to simply create a student class Student. It should be noted that when Java specifies object serialization, the class needs to implement the Serializable interface .

public class Student implements Serializable {
    private String name;
    private int age;
    private String number;
    private String classroom;
}

The next step is to implement the serialization of the object:

        Student s = new Student("石原里美",18,"001","智能一班");
        OutputStream os = new FileOutputStream("File//data.txt");
        ObjectOutputStream oos = new ObjectOutputStream(os);
        oos.writeObject(s);
        oos.close();

In addition, if you do not want some data in the object not to participate in serialization, you can modify it by transient , such as "private transient String name". After performing this operation, the data will display null when it is deserialized. .

Object deserialization 

  • Object bytes input stream, ObjectInputStream
  • Function: Based on memory, restore object data stored in disk files into objects in memory, which is called object deserialization
Constructor illustrate
public ObjectInputStream(InputStream is) wraps a low-level byte input stream into a high-level object byte input stream
method name illustrate
public Object readObject() Restore the object data stored in the disk file to the object in memory and return
        InputStream is = new FileInputStream("File//data.txt");
        ObjectInputStream ois = new ObjectInputStream(is);
        Object s = ois.readObject();
        System.out.println(s);
//输出结果:
//Student{name='石原里美', age=18, number='001', classroom='智能一班'}

There is another knowledge point. When defining a class, you can define a version serial number, and when deserializing the serial number, the serial number must be consistent before it can be read normally, such as "private static final long serialVersionUID = 1; "

If the version serial number in the class is changed after the first serialization, the deserialization will report an error before the second reserialization.

 

print stream 

  • Function: The print stream can realize convenient and efficient printing data to the file. Generally refers to PrintStream, WriteStream two classes
  • What data can be printed is what data, for example, printing the integer 97, writing it out is 97, printing boolean true, writing it out is true
Constructor illustrate
public PrintStream(OutputStream os) The print stream goes directly to the byte output stream pipe
public PrintStream(File f) The print stream goes directly to the file object
public PrintStream(String filepath) The print stream goes directly to the file path
method name illustrate
public void print(Xxx xx) print any type of data out

//三种构造器的使用
PrintStream ps = new PrintStream("File//data01.txt");
PrintStream ps1 = new PrintStream(new File("File//data.txt"));
PrintStream ps2 = new PrintStream(new FileOutputStream(new          File("File//data.txt")));
ps.print(11);
ps.print("凯里·欧文");

The difference between PrintStream and WriterStream :

  • The function of printing data is exactly the same, which is easy to use and efficient in performance.
  • PrintStream inherits the byte output stream OutputStream and supports methods for writing byte data
  • PrintWriter inherits the character output stream Writer and supports writing characters out

Properties

  • Function: Properties represents a properties file that can store the key-value pair information in its own object into a properties file
  • Properties file: The suffix is ​​a file ending with .properties, and the content in it is key=value, which will be used for system configuration information later.

Constructor illustrate
void load (InputStream is) Read a list of attributes (key-value pairs) from the input byte stream
void load (Reader r) Read a list of attributes (key-value pairs) from the input character stream
void store (OutputStream os,String comments) Write this list of properties (key-value pairs) into this Properties to output a byte stream in a format suitable for using the load(InputStream) method
void store(Writer w,String comments) Writes this list of properties (key-value pairs) into this Properties to output a stream of characters in a format suitable for using the load(reader) method
public Object setProperty(String key,String value) Save key-value pair (put)
public String getProperty(String key) 使用此属性列表中指定的键搜索属性值(get)
public Set<String> stringPropertyNames() 所有键的名称的集合(keySet())
        Properties properties = new Properties();
        properties.setProperty("石原里美","18");
        properties.setProperty("工藤静香","19");
        properties.setProperty("朱茵","20");
        System.out.println(properties);
        //第一个参数是文件存储路径,第二个是对文件的注释
        properties.store(new FileWriter("File//Baby.properties"),"这些都是绝世美女,不接受反驳哈哈哈");

        Properties properties = new Properties();
        properties.load(new FileReader("File//Baby.properties"));
        System.out.println(properties);
//输出结果:
//{"石原里美"=18,"工藤静香"=19,"朱茵"=20}

创作不易,给个三连吧

 

 

 

Guess you like

Origin blog.csdn.net/weixin_50635856/article/details/125633381