1. IO streams

1.1 INTRODUCTION to I/O Flows

I is input. O is output. Streaming refers to the transfer of data.

Data input and output through the Java programming language. In this case, file reads and writes.

So, in terms of reading, where does the data come from? In terms of writing, where does the data go?

Read: Loading data from the hard disk to memory, for example, viewing TXT documents through a Java program.

Write: To write data from memory to hard disk, for example by adding several characters to a TXT document through a Java program.

So, read and write operations are data transfer between memory and hard disk.

1.2 I/O Traffic Classification

1) According to the flow of data

  • Input stream: actually is the file read operation
  • Output stream: actually is the file write operation

2) According to the data transmission type

Byte stream Characters of the flow
Byte input stream Character input stream
Byte output stream Character output stream

1.3 Common SCENARIOS of I/O Flows

  • File upload
  • File download
  • Copy the file

Note: if we are working with binaries such as pictures, videos, etc. byte streams are preferred. If working with text files, character streams are preferred. If the type of file is not known, byte stream is preferred.

2. File operations: File class

Whether the file read operation or the file write operation is ultimately dealing with the file, so before learning Java IO we should first learn how to deal with the file.

The File class is the core class for processing files in Java, and here are some of the common methods.

1) Create a file

// I'm going to create a hello.txt file in the eclipse directory on drive D
File file = new File("D:\\eclipse\\hello.txt");
// Create a file
file.createNewFile();
Copy the code

2) Create a folder

// Create a folder named IDEA under eclipse on drive D
File file = new File("D:\\eclipse\\idea");
// Create a folder
file.mkdir();
Copy the code

3) Create multi-level folders

// Create multilevel folder \hello1\hello2 in eclipse folder on disk D
File file = new File("D:\\eclipse\\hello1\\hello2");
// Create a folder
file.mkdirs();
Copy the code

4) Check whether the directory is a file.

File file = new File("D:\\eclipse\\hello.txt");
// Check whether the directory is a file.
file.isFile();//true
Copy the code

5) Check whether the directory is a folder.

File file = new File("D:\\eclipse\\hello");
// Check whether this path is a folder.
file.isDirectory();//true
Copy the code

6) Check whether the file or folder in the directory exists.

File file = new File("D:\\eclipse\\hello.txt");
// Check whether the file or folder in this path exists.
System.out.println(file.exists());
Copy the code

7) Delete files/folders

File file = new File("D:\\eclipse\\hello.txt");
// Delete files or folders
file.delete();
Copy the code

3. The byte stream

3.1 byte output stream

FileOutputStream(String pathName) ¶Copy the code

Byte output stream usage steps:

  1. Creates a byte output stream object that takes the location of output to disk.
  2. Call the method that writes the data
  3. Free up resources (remember)

Here are some common methods for byte output streams:

1) Write one byte at a time write(int byte)

// Create a byte output stream object to write data to the specified file
FileOutputStream outputStream = new FileOutputStream("D:\\eclipse\\hello.txt");
// Write data one byte at a time, 97 for a
outputStream.write(97);
// Release resources
outputStream.close();
Copy the code

Execution Result:

2) Write one byte array at a time Write (byte[] bytes)

// Create a byte output stream object to write data to the specified file
FileOutputStream outputStream = new FileOutputStream("D:\\eclipse\\hello.txt");
// Write one byte array of data at a time
String str="helloworld"
byte[] bytes = str.getBytes();
outputStream.write(bytes);
// Release resources
outputStream.close();
Copy the code

Execution Result:

3) Write (byte[] bytes, int from, int len)

// Create a byte output stream object to write data to the specified file
FileOutputStream outputStream = new FileOutputStream("D:\\eclipse\\hello.txt");
// Writes data to the specified length of the byte array
String str="helloworld"
byte[] bytes = str.getBytes();
// Just the first two bytes
outputStream.write(bytes,0.2);
// Release resources
outputStream.close();
Copy the code

Execution Result:

4) Write data to line feed processing

Different operating systems handle:

  • Windows: \r\n
  • Linux system: \n
  • MAC system: \ R

The Following uses Windows as an example:

// Create a byte output stream object to write data to the specified file
FileOutputStream outputStream = new FileOutputStream("D:\\eclipse\\hello.txt");
String str="hello";
byte[] bytes = str.getBytes();
// Iterate over the byte array data
for (byte b : bytes) {
    outputStream.write(b);
    / / a newline
    outputStream.write("\r\n".getBytes());
}
// Release resources
outputStream.close();
Copy the code

Execution Result:

3.2 byte input stream

FileInputStream(String pathName)Copy the code

How to use byte input stream:

  1. Creates a byte input stream object
  2. Call the method that reads the data
  3. Free up resources (remember)

The following is a common approach to byte input streams:

1) Read data one byte at a time

// Create a byte input stream object to get the file at the specified location
FileInputStream inputStream = new FileInputStream("D:\\eclipse\\hello.txt");
int charStr ;
/ / inputStream. Read (read) data
//charStr = inputstream.read () assigns the read data to charStr
//charStr ! = -1 Checks whether the read data is null
while(( charStr = inputStream.read())! = -1){
    System.out.print((char)charStr);
}
// Release resources
inputStream.close();
Copy the code

Execution Result:

2) Read one byte array of data at a time

// Create a byte input stream object to get the file at the specified location
FileInputStream inputStream = new FileInputStream("D:\\eclipse\\hello.txt");
int charStr ;
byte[] bys = new byte[1024];
//inputStream.read(bys) Reads one byte array of data at a time
//charStr = inputstream.read (bys) Assigns the read data to charStr
//charStr ! = -1 Checks whether the read data is null
while(( charStr = inputStream.read(bys))! = -1){
    System.out.print(new String(bys,0,charStr));
}
// Release resources
inputStream.close();
Copy the code

Execution Result:

3.3 Byte Stream Application: Copy files

Think about it: If you want to copy a file, do you need to know where it is? Do I have to read the contents of the file after I get it? Read and write the contents of the file to another file at the same time?

Steps:

  1. Create a byte input stream object that reads the contents of the file
  2. Create a byte output stream object and write the file contents
  3. Read and write
  4. Free up resources (remember)
// To create a byte input stream object, which file do I copy from? That's where the file started
FileInputStream fileFrom = new FileInputStream("D:\\eclipse\\hello.txt");
// Create a byte output stream object, to which file should I copy it? That's the file destination
FileOutputStream fileTo = new FileOutputStream("D:\\eclipse\\world.txt");
// Read and write data (one byte array at a time, one byte array at a time)
byte[] bytes = new byte[1024];
int len;
while((len=fileFrom.read(bytes))! = -1) {
    fileTo.write(bytes,0,len);
}
// Release resources
fileFrom.close();
fileTo.close();
Copy the code

TXT file with the same contents as hello. TXT

3.4-byte buffer stream

3.4.1 Introduction to Buffer Flow

When we read a file with a very large amount of data, the reading speed will be extremely slow, which can affect our mood. So Java provides us with a buffer stream mechanism that can greatly improve the speed of file reads and writes.

3.4.2 Byte buffer stream

  • BufferedOutputStream: byte buffer output stream

  • BufferedInputStream: byte buffer input stream

They have an internal buffer through which to read and write, greatly increasing the speed of reading and writing IO streams.

1) Byte buffer output stream

FileOutputStream fos=new FileOutputStream("D:\\eclipse\\hello.txt");
// Bytes buffer output stream
BufferedOutputStream bos=new BufferedOutputStream(fos);
// write data 98 represents b
fos.write(98);
// Release resources
bos.close();
Copy the code

2) Byte buffered input stream

FileInputStream fis=new FileInputStream("D:\\eclipse\\hello.txt");
// Create a byte buffered input stream
BufferedInputStream bis=new BufferedInputStream(fis);
int len;
while((len=bis.read())! = -1){
    System.out.println((char)len);
}
// Release resources
bis.close();
Copy the code

3) Copy large files using byte buffer streams

// Where does the file I want to copy come from?
FileInputStream fis=new FileInputStream("D:\\eclipse\\oracle.zip");
// Create a byte input buffer stream
BufferedInputStream bis=new BufferedInputStream(fis);
// Where do I copy to?
FileOutputStream fos=new FileOutputStream("D:\\eclipse\\idea.zip");
// Create a byte output buffer stream
BufferedOutputStream bos=new BufferedOutputStream(fos);
int len=0;
byte[] ch=new byte[1024];
// Copy files while reading and writing
while((len=bis.read(ch))! = -1){
    bos.write(ch,0,len);
}
// Release resources
bos.close();
bis.close();
Copy the code

4. The characters of the flow

Before we talk about character streams, let’s talk about encoding and decoding.

Encoding: GBK, UTF-8, etc., you understand it as a data format that can be converted from one format to another.

Garbled: Encoding and decoding inconsistent, resulting in garbled. For example, if you use UTF-8 to encode a document, but use GBK to decode it, there will be a mismatch between characters and code values, resulting in garbled characters. As follows:

String tips="I love you China";
// Encodes the String as byte data using the specified character set
byte[] bys = tips.getBytes("GBK");
// Creates a string by decoding the specified byte array from the specified character set
String ss = new String(bys,"UTF-8");
System.out.println(":"+ss);
Copy the code

Execution Result:

Do you look confused? What the hell is this?

Java provides character streams because of the possibility of garbled characters from Chinese characters when using byte streams to manipulate characters.

Character stream: Add code (GBK, UTF-8, etc.) on the basis of byte stream to form a new data stream. Character stream = byte stream + encoding

The difference between character stream and byte stream: byte stream supports all file types such as sound, video, picture, and text, while character stream only supports text files.

4.1 Character output stream

FileWriter(String pathName) FileWriter(String pathName)Copy the code

Character output stream using steps:

  1. Creates a character output stream object
  2. Call the method that writes the data
  3. Free up resources (remember)
// Create a character output stream to write data to a file in the specified location
FileWriter fileWriter = new FileWriter(new File("D:\\eclipse\\hello.txt"));
// Write data
fileWriter.write("Hexia cool dream will come true!");
// Release resources
fileWriter.close();
Copy the code

Execution Result:

4.2 Character input stream

// Create the character input stream class FileReader(String pathName)Copy the code

Character input stream usage steps:

  1. Creates a character input stream object
  2. Call the method that writes the data
  3. Free up resources (remember)
// Create a character input stream
FileReader fileReader = new FileReader(new File("D:\\eclipse\\hello.txt"));
char[] bytes = new char[1024];
int len;
// Read data
while((len = fileReader.read(bytes)) ! = -1) {
    System.out.println(new String(bytes, 0, len));
}
// Release resources
fileReader.close();
Copy the code

Execution Result:

4.3 Character buffer stream

Character buffered stream: If a file is too large with too many characters, it can be used to improve efficiency.

  • BufferedReader: character buffered input stream
  • BufferedWriter: output stream of character buffering

1) Character buffered output stream

// Create a character buffered output stream
BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\eclipse\\haha.txt"));
bw.write("I love you China");
// The wrap method ADAPTS to different operating systems
bw.newLine();
bw.write("Ha ha ha ha ha.");
// Release resources
bw.close();
Copy the code

Execution Result:

2) Character buffered input stream

// Create a character buffered input stream
BufferedReader br = new BufferedReader(new FileReader("D:\\eclipse\\other.txt"));
// Read the file
String value;
// Read the data one row at a time and return the data as a string
while((value = br.readLine()) ! =null) {
    System.out.println(value);
}
br.close();
Copy the code

Execution Result:

3) The character buffer stream copies files

BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\eclipse\\student.txt"));
BufferedReader br=new BufferedReader(new FileReader("D:\\eclipse\\teacher.txt"));
String value="";
while((value=br.readLine())! =null) {
  bw.write(value);
  bw.newLine();
}
bw.close();
br.close();
Copy the code

4.4 transformation flows

Converts a byte stream into a character stream, using the specified encoding to read or write to the data stream.

  • InputStreamReader: Converts a byte input stream into a character input stream
  • OutputStreamWriter: Converts a byte output stream into a character output stream

1) A byte input stream is replaced by a character input stream

InputStreamReader isr = new InputStreamReader(new
FileInputStream("D:\\eclipse\\haha.txt"),"GBK");
// Read data one character at a time
int str;
while((str=isr.read())! = -1) {
System.out.print((char)str);
}
isr.close();
Copy the code

2) A byte output stream is converted to a character output stream

OutputStreamWriter osw = new OutputStreamWriter(new
FileOutputStream("D:\\eclipse\\haha.txt"),"GBK");
osw.write("Go China!"); 
osw.close();
Copy the code

5. The Properties is introduced

Introduce the Properties:

  • Properties is a Map architecture collection class
  • Properties can save/load data
  • Properties The key-value pairs in the property list are all strings

1) Map set

Properties properties = new Properties();
properties.setProperty("name"."jay");
properties.setProperty("age"."18");
Set<String> keys = properties.stringPropertyNames();
for (String key : keys) {
    System.out.println(key);
    String value = properties.getProperty(key);
    System.out.println(key + "," + value);
}
Copy the code

Execution Result:

2) Load data from the data stream

Properties prop = new Properties();
FileReader fileReader = new FileReader("D:\\resources\\jdbc.properties");
prop.load(fileReader);
System.out.println(prop);
System.out.println(prop.getProperty("username"));
System.out.println(prop.getProperty("password"));
System.out.println(prop.getProperty("driver"));
fileReader.close();
Copy the code

Execution Result:

6. Object serialization && deserialization

6.1 Object Serialization

Object serialization: Saving an object to disk or transferring it over the network.

Object serialization stream: ObjectOutputStream

Note: For an object to be serialized, the class to which the object belongs must implement the Serializable interface

Here is sample code for object serialization:

The user types:

public class User implements Serializable {

    private String username;

    private int age;

    public User(String username, int age) {
        this.username = username;
        this.age = age;
    }

    public String getUsername(a) {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge(a) {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString(a) {
        return "User{" +
                "username='" + username + '\' ' +
                ", age=" + age +
                '} '; }}Copy the code

Serialization method:

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\resources\\user.txt"));
// Create an object
User user = new User("zhangsan".12);
// Writes the specified object to the ObjectOutputStream
oos.writeObject(user);
// Release resources
oos.close();
Copy the code

6.2 Object deserialization

Object deserialization: Convert files to objects. In plain English, it reads data and then converts it to objects.

Object deserialization stream: ObjectInputStream

Sample code:

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\resources\\user.txt"));
//Object readObject(): Reads an Object from ObjectInputStream
Object object = ois.readObject();
User user = (User) object;
System.out.println(user.getUsername() + "," + user.getAge());
// Release resources
ois.close();
Copy the code

Execution Result:

Wechat official account: Eclipse programming. Focus on programming technology sharing, adhere to lifelong learning.