preface

Hello, everyone, I am Tang Yuan, today to bring you is “Java IO flow – introduction”, I hope to help you, thank you

Because there are many Java IO classes, this leads to me at the beginning of learning, I feel very confused, every time I use the Internet search, the result of each time after use forget;

Later, when I settled down to read and study, I realized that there were rules.

Here is a simple introduction, as an entry-level tutorial, there are a lot of things to learn, free to organize it again.

Introduction to the

File IO streams, there are two main ways

  1. Byte stream: based on various files, including plain text TXT, audio file MP3, video file MP4 and so on
  2. Character stream: Based on plain text strings, such as plain text TXT, etc

The related classes used in this example are as follows:

All read and write operations are in memory, because that’s where the program is running

A read operation is a read from a disk file or network stream into memory, which in memory is Input

A write operation is to write from memory to a disk file or network stream, which in memory is Output

These two methods are described below

Byte stream

In this example, the byte stream will focus on ObjectInputStream and ObjectOutputStream. These two classes are for reading and writing normal Java objects, because they can also be used to serialize and deserialize Java objects

The typical application scenario is that a Java program on one machine writes an object to a file, and then transfers it to a Java program on another machine to read the object in the file

When a Java object is written, the Java object is serialized (the object is converted to bytes) and then written

When a Java object is read, it is deserialized (bytes into objects) and then read

Write the object

To write an object to a file, you need to serialize the object first, and then write the serialized bytes to the file.

Serialization is the conversion of an object’s attribute information to a series of bytes (excluding transient type attributes, described below).

The general process is as follows:

Read the object

To read an object from a file, deserialize it, then convert it to the corresponding Java object and restore the object property values

Deserialization is converting a sequence of bytes into a real object instance (excluding transient type attributes)

The general process is as follows:

transient

The modifier literally means instantaneous, transient

When applied to a property of an object, it means that the property is temporary and will expire when serialized

When deserialized, this property will be null (if the property is an object reference) or the default value of the underlying type (if the property is an underlying type)

For example, privacy attributes such as passwords can be set as TRANSIENT, so that they will not be intercepted in the transmission process and the password can be cracked

code

public class ObjectIoDemo {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        InnerObject object1 = new InnerObject(10);
        String filename = "object.bin";
        writeObjectFun(filename, object1);
        InnerObject objectReturn = (InnerObject) readObjectFun(filename);
        System.out.println(objectReturn);

    }

    // Write the object to the specified file
    public static void writeObjectFun(String filename, Object o) throws IOException {
        FileOutputStream fileOutputStream = new FileOutputStream(filename);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(o);
        // Close the stream. FileOutputStream is closed
        objectOutputStream.close();
    }

    // Read the object from the specified file
    public static Object readObjectFun(String filename) throws IOException, ClassNotFoundException {
        FileInputStream fileInputStream = new FileInputStream(filename);
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        Object o = objectInputStream.readObject();
        // Close the stream, fileInputStream will be closed
        objectInputStream.close();
        returno; }}class InnerObject implements Serializable{

    @Override
    public String toString(a) {
        return "InnerObject{" +
                "num=" + num +
                '} ';
    }

    public InnerObject(int num) {
        this.num = num;
    }

    public int getNum(a) {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    private int num;
}

Copy the code

If the Java object to be written is not serialized, the following error is reported

Exception in thread "main" java.io.NotSerializableException: com.jalon.basic.io.InnerObject
	at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
	at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
	at com.jalon.basic.io.ObjectIoDemo.writeObjectFun(ObjectIoDemo.java:28)
	at com.jalon.basic.io.ObjectIoDemo.main(ObjectIoDemo.java:19)
Copy the code

Character stream: Based on plain text strings

Data written to a file by a character stream is treated as generic text data so that Java programs and other programs can read and write the file

Write the text

The general process is as follows:

Read the text

The general process is as follows:

BufferedReader and BufferedWriter

Why use a buffer? Can’t you just use FileReader and FileWriter?

FileWriter and FileReader can be used directly, but not efficiently, because every read and write is performed on disk.

The BufferedWriter and BufferedReader buffers reduce the number of reads and writes to the disk.

BufferedReader: a program can read a lot of data from disk to the buffer at once, read from the buffer again, wait until the buffer is empty and then read from disk again.

BufferedWriter: A program can write to the buffer multiple times and write to the disk once the buffer is full

code

public class TextIoDemo {
    public static void main(String[] args) throws IOException {
        String filename = "string.txt";
        writeString(filename, "hello world");
        String res = readString(filename);
        System.out.println(res);
    }
	// Write a string to the specified file
    public static void writeString(String filename, String content) throws IOException {
        FileWriter fileWriter = new FileWriter(filename);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(content);

        bufferedWriter.close();
    }
	// Reads the string from the specified file
    public static String readString(String filename) throws IOException {
        FileReader fileReader = new FileReader(filename);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String line = "";
        StringBuilder stringBuilder = new StringBuilder();
        while((line=bufferedReader.readLine())! =null){
            stringBuilder.append(line);
        }
        bufferedReader.close();
        returnstringBuilder.toString(); }}Copy the code

conclusion

IO streams are divided into byte streams and character streams

Byte streams can handle a variety of file formats, but are inefficient

Character streams can only handle text formats, but they are efficient

The above list is only a few read and write classes, there are many more Java read and write classes, you can go to java.io to check

reference

  1. Head First Java (2nd edition)
  2. Java Core Technology Volume 1 (10th Edition)
  3. Ideas for Java Programming (4th edition)

Afterword.

And finally, thank you for watching. Thank you