preface
Today, let's talk about the operation of files in Java, IO stream (input / output stream). First, in the computer, the information set of files on the computer can be text, pictures, videos, etc. Files are stored in binary
Input and output streams
Input stream: an object from which a sequence of bytes can be read is called an input stream
Output stream: an object from which a sequence of bytes can be written is called an output stream
The source and destination of character sequences can be files (usually), network connections, memory blocks, etc
IO stream common classes
InputStream and OutputStream
In common classes, abstract classes InputStream and OutPutStream form the basis of the input and output class hierarchy. They are also called byte input / output streams. They are the parent of all class byte input / output streams.
Class diagram:
Reader and Writer
Because the byte stream takes one byte as the basic unit of processing, it is not particularly convenient to process the information (text information) stored in Unicode, because each character is represented by multiple bytes in Unicode. One of the abstract classes Reader and Writer inherits a separate class hierarchy dedicated to handling Unicode characters. They read and write based on the Char value of two bytes (i.e. a Unicode symbol), rather than one byte
Class diagram:
Use of IO streams
Operations on files
Byte stream is recommended for non text files
package com.cheng.IOLearn; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class FileCopy { public static void main(String[] args) { // 1. Create the input stream of the file and read the file into the program // 2. Create a file to the output stream and write the read file data to the specified file FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; String filePath = "//Users//chenzouquan//Desktop / / unnamed folder / / screenshot 2021-10-20 5.21.49.png "; String destPath = "//Users//chenzouquan//Desktop / / unnamed folder / / text.png "; try { fileInputStream = new FileInputStream(filePath); fileOutputStream = new FileOutputStream(destPath); // Define a byte array to improve reading efficiency byte[] buf = new byte[1024]; int readLen = 0; while ((readLen = fileInputStream.read(buf)) != -1){ // After reading, it is written to the file, that is, read and write fileOutputStream.write(buf,0,readLen);// Be sure to use this method } System.out.println("Success copy "); } catch (IOException e) { e.printStackTrace(); }finally { // Closed flow try { if (fileInputStream != null){ fileInputStream.close(); } if (fileOutputStream != null){ fileOutputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
Byte stream is recommended for text files
package com.cheng.IOLearn; import java.io.FileReader; import java.io.IOException; public class LearnFileReader { public static void main(String[] args) { // 1. Specify text path String strPath = "//Users//chenzouquan//Desktop / / unnamed folder / / test.txt "; // 2. Create the input stream of the file and read the file into the program FileReader fileReader = null; int data = 0; try { fileReader = new FileReader(strPath); // After reading, it is written to the file, that is, output while reading while( (data = fileReader.read()) != -1){ System.out.print((char) data); } } catch (IOException e) { e.printStackTrace(); } finally { // Closed flow try { fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Key points of operation: after performing input and output operations, you must remember to close or flush , the reason why the responsible file cannot be saved is that there is no real modification of the file before the program executes close or flush, but the formal modification of the file is carried out in the execution of close or flush method. The flush method will be executed in the close method, so we generally only need to close the flow.
Node flow and processing flow
Node stream: you can read and write from one data source (such as FileReader/FileWriter,FileInputStream/FileOutputStream...)
Processing flow: wrap a node flow or processing flow, expand their business, and provide programs with better reading and writing functions (such as BufferedReader/BufferedWriter...)
From the source code, the decorator mode is used here: that is, store an object to be operated in a decorator object, and operate the object in the decorator object
Taking BufferedReader as an example, it has the attribute Reader, so it can encapsulate the Reader subclass for operation
package com.cheng.IOLearn; public abstract class Reader_ { public void Reader_File() { } } class FileReader_ extends Reader_{ @Override public void Reader_File(){ System.out.println("FileReader_"); } } class StringReader_ extends Reader_{ @Override public void Reader_File(){ System.out.println("StringReader_"); } } /** * Processing flow / packaging flow */ class BufferedReader_ extends Reader_{ private Reader_ reader; public BufferedReader_(Reader_ reader) { this.reader = reader; } // The corresponding functions can be extended below }
Object stream (serialization and deserialization)
serialize
Store several data types including
Int num; char a; String str;
public class TestObjectOutputStreamLearn { public static void main(String[] args) throws IOException { // Serialize save file location String path = "//Users//chenzouquan//Desktop / / unnamed folder / / data.dat "; ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path)); // Serialize data oos.write(100); oos.writeChar('a'); oos.writeUTF("test"); // Serializing objects requires that the objects to be serialized implement the Serializable interface oos.writeObject(new Cat()); // Closed flow oos.close(); System.out.println("Serialization complete"); } }
Java object
public class Cat implements Serializable { // Provide the serialization version number, so that it will be considered as an update rather than a new class when serializing and deserializing after class modification private static final long serialVersionUID = 1L; private String name = "hello"; int age = 11; public String CarName(){ return this.name; } public Cat(String name, int age) { this.name = name; this.age = age; } public Cat() { } }
Deserialization
public class TestObjectOutputStreamLearn { public static void main(String[] args) throws IOException, ClassNotFoundException { // file location String path = "//Users//chenzouquan//Desktop / / unnamed folder / / data.dat "; ObjectInputStream oos = new ObjectInputStream(new FileInputStream(path)); // The read data should be consistent with the serialization order int i = oos.readInt(); char c = oos.readChar(); String s = oos.readUTF(); System.out.println(i+c+s); Object o = oos.readObject(); // If you use the methods and properties of the original object, convert it to the original object Cat cat = (Cat) o; cat.CarName(); oos.close(); } }