Java_IO stream (Intensive)

Keywords: Java JavaSE

1. Concept of Java Io flow

Stream: represents any data source object capable of producing data or receiving end object capable of receiving data.

The essence of flow: data transmission. According to the characteristics of data transmission, the flow is abstracted into various types to facilitate more intuitive data operation.

Function: establish a transport channel for data source and destination

The model adopted by Java IO is excellent in its IO model design. It uses Decorator[ ˈ dek ə re ɪ t ə (r) ] (Decorator) mode, divided by function ː m] English [stri ː m] Beauty, you can dynamically assemble these streams to get the functions you need.

For example, if you need a buffered file input stream, you should use a combination of FileInputStream (character stream) and bufferedinputstream (byte stream).  

According to the flow direction, the flow can be divided into input flow and output flow.

  • Input stream: data can only be read from, not written to.
  • Output stream: data can only be written to it, not read from it.

According to the division of operation units, it can be divided into byte stream and character stream.

The usage of byte stream and character stream is almost the same. The difference is that the data units operated by byte stream and character stream are different. The unit operated by byte stream is the data unit, which is 8-bit byte, and the character stream operates the data unit, which is 16 bit character.  

Five classes and one interface commonly used by IO streams

In the whole Java.io package, the most important is five classes and one interface.

The five classes refer to File, OutputStream, InputStream, Writer and Reader;

An interface refers to serializable. If you master the core operations of these IO, you will have a preliminary understanding of the IO system in Java.

2,File

File is a standard file class. The file class object corresponds to a directory or file in the file system. The file class object describes the attributes such as file path, name, length and readability. It can be used to name files, query file attributes or process directories, but it cannot read or write files.

Common attributes and functions of file operation (read class):  

file.separator;//Directory symbol for the system and / or\
pathSeparator;//Is the separator of the system;
exists();//Determine whether this file exists
isFile();//Judgment is file
isDirectory();//It's a directory
getName();//file name
getPath();//Entire pathname / relative pathname
length();//File length (size)
canRead();//File read properties
canWrite();//File write properties
getAbsolutePath();//Obtain the file path. If it is a relative path, complete it according to the project path
lastModified();//Last modification time

Test code:

package IO_test;

import java.io.File;

/**
 * @author laoshifu
 * @date 2021 November 28
 */
public class Action {
    public static void main(String[] args) {
        File file=new File("E:/");
        System.out.println(file.separator);//Directory symbol for the system and / or\
        System.out.println(file.pathSeparator);//Is the separator of the system;
        System.out.println(file.exists());//Determine whether this file exists
        System.out.println(file.isFile());//Judgment is file
        System.out.println(file.isDirectory());//It's a directory
        System.out.println(file.getName());//file name
        System.out.println(file.getPath());//Entire pathname / relative pathname
        System.out.println(file.length());//File length (size)
        System.out.println(file.canRead());//File read properties
        System.out.println(file.canWrite());//Is it writable
        //Obtain the file path. If it is a relative path, complete it according to the project path
        System.out.println(file.getAbsolutePath());
        System.out.println(file.lastModified());//Last modification time
        System.out.println(file.getPath());//Entire pathname / relative pathname
    }
}

effect:

Common attributes and functions of file operation (operation class):   

renameTo(new File);rename
delete();Delete directory
mkdir();Create directory
mkdirs();Create multi tier directory
createNewFile();create a new file

Test code:

package IO_test;

import java.io.File;
import java.io.IOException;

/**
 * @author laoshifu
 * @date 2021 November 28
 */
public class Action {
    public static void main(String[] args) {
        //rename
        File file=new File("E:/test/demo.txt");
        file.renameTo(new File("E:/test/demo1.txt"));
        //Create a single tier directory
        File fileMk=new File("E:/test/demo");
        fileMk.mkdir();
        //Create multi tier directory
        File fileMks=new File("E:/test/demo/a/b/c/d/e/f/g");
        fileMks.mkdirs();
        //Delete directory
        File delDir=new File("E:/test/demo/a/b/c/d/e/f/g");
        delDir.delete();
        //create a file
        File fileCreate=new File("E:/test/demo/file.txt");
        try {
            fileCreate.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

effect:

Exercise:

1,The basic unit of character stream processing data is( A ). 
	A,2 byte					B,1 byte
	C,1024 byte				D,1024B

2,An existing Chinese article is.txt File, which stream operation should we use( B ),because( D ). 
	A,Byte stream		
	B,Character stream
	C,Byte stream reads one byte at a time, and any file can be operated			
	D,Because it is Chinese, one Chinese occupies 2 characters, and there will be garbled code when reading with byte stream, so character stream is adopted. There will be no coding error when reading 2 characters each time.

3,file.getPath()And file.getAbsolutePath()What's right is(Multiple choice)( BD ). 
A,getPath The absolute location of the file must be returned
B,getAbsolutePath The absolute location of the file must be returned
C,The default relative path returns the same result
D,The default absolute path returns the same result

Obtaining all file names under disk E is an example:

//Package required
import java.io.File;
import java.util.Arrays;
//code
File f = new File("E:/");
String []s = f.list();
System.out.println(Arrays.toString(s));
//Obtain the paths of all the files on disk E:
File [] files = f.listFiles();
System.out.println(Arrays.toString(files));
//Get system drive letter
File [] files1 = File.listRoots();
System.out.println(Arrays.toString(files1));

3. File reading of character stream

Why read a text file with a character stream:

1. Since the space occupied by each Chinese is 2 bytes, using byte stream to read will produce garbled code

2. Each Chinese occupies 2 bytes, which is the same size as char. All Chinese correspond to a char value

Read plain text, steps:

1. Establish contact object

2. Select stream: Reader FileReader

3. Read: char[] flush=new char[1024]; / / or read one by one

4. Close resource fr.close()

Byte stream read file VS character stream read plain text

1. The use of stream is different. The former uses "stream" and the latter is "reader"

2. Different arrays are used for reading. The former is byte array and the latter is char array

3. The speed is different, and the latter is faster than the former

Single read:

Coding example:

package IO_test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author laoshifu
 * @date 2021 November 28
 */
public class Action {
    public static void main(String[] args) {
        FileReader fr = null;
        try {
            fr = new FileReader(new File("E:/test/demo1.txt"));
            int read=fr.read();
            System.out.println((char)read);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

effect:

Cyclic read:

Coding example:

package IO_test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author laoshifu
 * @date 2021 November 28
 */
public class Action {
    public static void main(String[] args) {
        FileReader fr = null;
        try {
            fr = new FileReader(new File("E:/test/demo1.txt"));
            while (true) {
                int read = fr.read();
                if (read == -1) {
                    break;
                }
                System.out.print((char) read);
            }
            } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Execution effect:

4. Character stream write

Write test:

Coding example:

package IO_test;

import java.io.*;

/**
 * @author laoshifu
 * @date 2021 November 28
 */
public class Action {
    public static void main(String[] args) throws IOException {
        FileWriter fw= null;
        try {
            fw = new FileWriter(new File("E:/test/demo1.txt"));
            fw.write("I HAVE A GOOD IDEA!");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            fw.flush();//Refresh, you must brush it after writing
            fw.close();
        }
//You can write one string at a time,
//After unified writing, you need to refresh, write the data to the corresponding file, and empty the cache
//Close after reading, fw.close(); it is usually written in finally
    }
}

Exercise:

1,FileReader fr Is it a file or a string read( A ). 
	A,file					B,character string

2,Character stream FileWriter stay write Which function must be executed after a string to write data into the corresponding file( B ). 
	A,writed()		
	B,flush()
	C,wait()			
	D,closes()

3,FileWriter in flush The function is( B ). 
	A,Refresh data in buffer				 	B,Empty the buffer and complete the file write operation
	C,Close write stream					 	D,Reopen buffer

5. Character stream copy file

Copy a separate copy of the files in a folder, and paste a copy after modifying the name in the same folder.

1. Read the source file.

2. Read one by one through FileReader.

3. Write the character stream read one by one to the pre given position through FileWriter.

4. Close the write stream and close the read stream.

Coding example:

package IO_test;

import java.io.*;

/**
 * @author laoshifu
 * @date 2021 November 28
 */
public class Action {
    public static void main(String[] args) throws IOException {
        FileReader fr = new FileReader(new File("E:/test/demo1.txt"));
        FileWriter fw = new FileWriter(new File("E:/test/demo2.txt"));
        int i = 0;
        char[] geshu = new char[10];
        while (true) {
            i = fr.read(geshu);
            if (i == -1) {
                break;
            }
            fw.write(geshu, 0, i);fw.write(i);
        }
        fw.flush();//Slow inside, fast outside
    }
}

The effects are as follows:  

Exercise:

1,use Java IO In the process of reading and writing text files by stream, you need to deal with the following(  B  )Abnormal.
	A,ClassNotFoundException					B,IOException
	C,SQLException								D,RemoteException

2,stay Java of IO In operation(  D  )Method can be used to brush the buffer of a new stream.
	A,void release()		B,void close()
	C,void remove()			D,void flush()

3,For FileReader fr=new FileReader("url.txt")The return value of the method is correct(  B  ). 
	A,String str=fr.read();
 	B,int str=fr.read();
	C,byte str=fr.read();
	D,char str=fr.read();

6. Concept of byte stream

IO: data flows from hard disk to memory (Input) or from memory to hard disk (Output).

By operation data unit:

Byte stream, character stream

|-Byte stream: 8 bits

|-Character stream: 16 bits

It can operate all files, including text files, video, audio, compressed files, etc. it can be read and written by byte stream.  

Byte stream

Character stream

Input stream

InputStream

Reader

Output stream

OutputStream

Writer

Coding example:

package IO_test;

import java.io.*;

/**
 * @author laoshifu
 * @date 2021 November 28
 */
public class Action {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = null;FileOutputStream fos = null;
        try {//Copy a copy of the file to the same folder and change the name
            fis = new FileInputStream(new File("E:\\test\\DoodDB.sql"));
            fos = new FileOutputStream(new File("E:\\test\\DoodDB1.sql"));
            byte[] buf = new byte[1024];//1024 bytes read at a time (1024b)
            while (true) {
                int i = fis.read(buf);
                if (i == -1) {break;}//When reading is not available, the cycle ends
                fos.write(buf, 0, i);//The 1024b read each time is stored in the write buffer
            }		fos.flush();//Empty the buffer and write the contents to the new file
            fos.close();fis.close();//Turn off read / write stream
        }catch (Exception e) {			e.printStackTrace();		}

    }
}

effect:

Exercise:

1,Data flows from hard disk to memory( A ),Or flow from memory to hard disk( D ). 
	A,Input					B,Read
	C,Write					D,Output

2,The files whose byte stream is not good at manipulation are( B ). 
	A,picture		B,Chinese text		C,video		D,music

3,Which of the following functions are not FileOutputStream of write Overloading method of function ( D ). 
	A,write(byte[]b)				 				B,write(int b)
	C,write(byte[]b,int off,int len)			D,write(byte b,int len)

The above is all the commonly used contents of [Java_IO]. I hope it can be helpful to you, but there are some exceptions that are easy to occur in [server], which are not summarized due to the trouble of reproduction.

For example:[ Relative path of IO stream file and method of obtaining system path Hongmu fragrance CSDN blog]

Hope you can help, can collect, high value.

Posted by Fritz.fx on Sun, 28 Nov 2021 17:47:30 -0800