IO stream and File class

Keywords: Java C R Language c1

1. IO stream object

IO: input output IO is used to flow data from one device to another

Data files flow from disk to memory, from disk to mobile storage device, and from one computer to another

Everything is bytes: any data file is composed of bytes, and bytes are the smallest storage unit in the computer (Java source code, games, music, movies)

[external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-T6P02yZV-1638094702871)(img / input and output. JPG)]

1.1 classification of IO stream objects

1.1.1 classification by document type of operation

  • Text type file – select stream object character stream
    • What is a text file: after opening the file with text tools, Notepad + +, EDITPLUS, humans can read it directly
  • Non text type file – select stream object byte stream

1.1.2 classification according to data flow direction

  • Input stream: Java programs read data from other places
  • Output stream: data in a Java program written elsewhere

1.1.3 classification and induction of IO flow objects

  • Byte output stream: OutputStream abstract class
  • Byte input stream: InputStream abstract class
  • Character output stream: Writer abstract class
  • Character input stream: Reader abstract class

2. Byte output stream

java.io.OutputStream is a superclass of all byte output streams: it can write to any type of file

  • Method of writing bytes write
    • void write(int b) writes a single byte
    • void write(byte[] b) writes a byte array
    • void write(byte[] b,int off,int len) writes a part of the array, including the start index and the number of writes

2.1 FileOutputStream

  • Construction method: fileoutputstream (file)
  • Construction method: FileOutputStream(String file)
    • Create a byte output stream object, and the binding parameter is the data destination to be written

The JVM is very smart: any operating system has IO capability. The JVM relies on the operating system to realize IO function. After the IO stream object is used, it needs to release resources

2.2 steps for writing byte output stream to file

  • Create a byte output stream object. In the construction method, bind the file path and write the destination
  • Call the write method of the stream object to write data
  • Release resources

2.3 write a single byte

    /**
     * Write a single byte
     * new FileOutputStream("c:/1.txt"); If the file is not created, it will be overwritten
     */
    public static void writeByte() throws IOException {
        //Create a byte output stream object. In the construction method, bind the file path and write the destination
        FileOutputStream fos = new FileOutputStream("c:/1.txt");
        //Write a single byte
        fos.write(45);
        fos.write(49);
        fos.write(48);
        fos.write(48);
        //Release resources
        fos.close();
    }

2.4 write byte array

    /**
     * Write byte array
     */
    public static void writeByteArray() throws IOException {
        //Create a byte output stream object. In the construction method, bind the file path and write the destination
        FileOutputStream fos = new FileOutputStream("c:/1.txt");
        byte[] bytes = {97,98,99,100,101,102};
        //Write byte array
        fos.write(bytes);
        //Write byte array Chinese
        fos.write("Hello,I'm fine,hello everyone".getBytes());
        //Write part of array
        fos.write(bytes,1,3);
        //Release resources
        fos.close();
    }

2.5 add write and line feed

  • Append write, and write true for the second parameter of the FileOutputStream construction method
  • Newline write, using the newline symbol of the Windows system \ r\n
    /**
     * Append write and wrap
     */
    public static void writeAppend()throws IOException {
        //Create a byte output stream object. In the construction method, bind the file path and write the destination
        FileOutputStream fos = new FileOutputStream("c:/1.txt",true);
        fos.write(65);
        //Write newline symbol
        fos.write("\r\n".getBytes());
        fos.write(66);
        //Release resources
        fos.close();
    }

2.6 IO exception handling

    /**
     *  try catch Exception handling: close() is written in finally
     */
    public static void write2()  {
        //Promote scope: variables are defined outside of try, and objects are created by try
        FileOutputStream fos = null;
        FileOutputStream fos2 = null;
        try {
            //Create a byte output stream object. In the construction method, bind the file path and write the destination
            fos = new FileOutputStream("c:/1.txt");
            fos2 = new FileOutputStream("c:/2.txt");
            //Write a single byte
            fos.write(45);
            fos.write(49);
            fos.write(48);
            fos.write(48);
        }catch (IOException ex){
            ex.printStackTrace();
        }finally {
            //Release resources
            try {
                //Failed to create stream object. The value of fos variable is null. close cannot be called
                if(fos != null)
                    fos.close();
            }catch (IOException ex){
                ex.printStackTrace();
            }

            //Release resources
            try {
                //Failed to create stream object. The value of fos variable is null. close cannot be called
                if(fos2 != null)
                    fos2.close();
            }catch (IOException ex){
                ex.printStackTrace();
            }
        }
    }


    /**
     *  try catch Exception handling: close() is written in finally
     */
    public static void write()  {
        //Promote scope: variables are defined outside of try, and objects are created by try
        FileOutputStream fos = null;
        try {
            //Create a byte output stream object. In the construction method, bind the file path and write the destination
            fos = new FileOutputStream("q:/1.txt");
            //Write a single byte
            fos.write(45);
            fos.write(49);
            fos.write(48);
            fos.write(48);
        }catch (IOException ex){
            ex.printStackTrace();
        }finally {
            //Release resources
            try {
                //Failed to create stream object. The value of fos variable is null. close cannot be called
                if(fos != null)
                    fos.close();
            }catch (IOException ex){
                ex.printStackTrace();
            }
        }
    }

3. Byte input stream

java.io.InputStream is a superclass of all byte input streams: it can read any type of file

  • Method to read bytes (read)
    • int read() reads a single byte and returns - 1 at the end of the stream
    • int read(byte[] b) reads the byte array and returns - 1 at the end of the stream

3.1 FileInputStream

  • Construction method: FileInputStream (file)
  • Construction method: FileInputStream(String file)
    • Create a byte input stream object, and the binding parameter is the data source file to be read

3.2 byte input stream reads a single byte

    /**
     * Byte input stream, reading a single byte
     * int read() Read single byte
     */
    public static void readByte()throws IOException {
        //Create byte input stream object and bind data source file
        FileInputStream fis = new FileInputStream("c:/1.txt");
        //Read a single byte
        //Loop read, condition read()=- Just one
        int r = 0;
        while ( (r = fis.read()) !=-1){
            System.out.print((char) r);
        }
        //Release resources
        fis.close();
    }

3.3 byte input stream reading byte array

    /**
     * Byte input stream, read byte array
     * int read(byte[] b) Read byte array
     * Return value: returns the number of bytes read
     * String Class constructor new string (byte array, start index, number of conversions)
     */
    public static void readByteArray()throws IOException{
        //Create byte input stream object and bind data source file
        FileInputStream fis = new FileInputStream("c:/1.txt");
        byte[] bytes = new byte[50];
        //Define variables and save the return value of the read method
        int r = 0 ;
        while ( (r=fis.read(bytes)) !=-1){
            System.out.print(new String(bytes,0,r));
        
        fis.close();
    }

4. Document copying

Realize the file copy function. It is the same as Ctrl + C and Ctrl + V in the operating system. In principle, it is byte moving

   /**
     * File replication is the reading and writing of IO stream objects
     * Improve efficiency using arrays
     */
    public static void copy_1()throws IOException {
        //Byte input stream, binding data source file
        FileInputStream fis = new FileInputStream("c:/1.avi");
        //Byte output stream, binding the destination file to be copied
        FileOutputStream fos =  new FileOutputStream("e:/1.avi");
        //Byte array buffer
        byte[] bytes = new byte[1024];
        //Define variables and save the return value of the read method read
        int r = 0;
        //Loop reading data source file
        while ( (r=fis.read(bytes)) != -1){
            //Byte output stream, write byte array, start with 0 index, write and read the number
            fos.write(bytes,0,r);
        }
        fos.close();
        fis.close();
    }

5. Buffer stream of byte stream

The buffer stream of byte stream is used to improve the reading and writing performance of the original stream object

Byte stream buffer stream, which is also byte stream in essence

  • Bufferedouptstream inherits OutputStream
    • The write() method writes a single byte, or an array of bytes
  • BufferedInputStream inherits InputStream
    • The method read() reads a single byte and reads an array of bytes

6.1 bufferedouptstream construction method

Bufferedouptstream (OutputStream out) pass byte output stream

The stream starting with Buffered is called Buffered stream and FileOutputStream is the basic stream

New bufferedouptstream (New fileoutputstream()) operates efficiently on which basic stream it passes

6.2 BufferedInputStream construction method

BufferedInputStream(InputStream in) pass byte input stream

new BufferedInputStream(new FileInputStream())

  /**
     *  File replication, buffer stream implementation, high efficiency
     */
    public static void copy_2()throws IOException {
        //Byte input stream, binding data source file
        FileInputStream fis = new FileInputStream("c:/1.avi");
        //Byte output stream, binding the destination file to be copied
        FileOutputStream fos =  new FileOutputStream("e:/1.avi");
        //Create a buffer stream of byte input stream to improve the efficiency of the original byte input stream
        BufferedInputStream bis = new BufferedInputStream(fis);
        //Create a buffer stream of byte output stream to improve the efficiency of the original byte output stream
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        //Byte array buffer
        byte[] bytes = new byte[1024];
        //Define variables and save the return value of the read method read
        int r = 0;
        while ( (r = bis.read(bytes)) !=-1){
            bos.write(bytes,0,r);
        }
        bis.close();
        bos.close();
}

6. Character stream

Only text files can be operated. The so-called text files are those that can be edited and opened with notepad, notepad + + and other text, and can not affect normal reading.

  • The Writer class is the parent class of all character output streams (write to text files)
    • write(int c) writes a single character
    • write(char[] ch) writes the character array
    • write(char[] ch,int off,int len) writes a part of the character array, starts the index, and the number of writes
    • write(String str) writes a string
    • void flush() flushes the buffer of the stream (write data to memory first). Only after the data is flushed can it reach the destination file
  • The Reader class is the parent class of all character input streams (reading text files)
    • int read() reads a single character
    • int read(char[] ch) reads the character array

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-s7Zhp3jV-1638094702877)(img / conversion stream. JPG)]

7.1 OutputStreamWriter class

OutputStreamWriter inherits the Writer and is both the output stream of characters and the conversion stream

Character stream = byte stream + encoding table

OutputStreamWriter conversion stream: a bridge between character flow and byte stream, and characters are converted into bytes

  • Construction method:

    • OutputStreamWriter(OutputStream out) passes an arbitrary byte output stream
    • OutputStreamWriter(OutputStream out,String encoding table name) passes an arbitrary byte output stream
  • Convert stream to write character file, UTF-8 encoding

    /**
     *  Use coding table, UTF-8
     */
     public static void writeUTF8()throws IOException {
         //Create byte output stream
         FileOutputStream fos = new FileOutputStream("c:/utf.txt");
         //Create a conversion stream object and construct an output stream that passes bytes
         OutputStreamWriter osw = new OutputStreamWriter(fos);//utf-8 encoded output is used by default
         //Write string
         osw.write("Hello");
         //Refresh stream
         osw.flush();
         //Resource release
         osw.close();
     }
  • Convert stream write character file GBK encoding
    /**
     * Using the coding table, GBK
     */
    public static void writeGBK()throws IOException{
        //Create byte output stream
        FileOutputStream fos = new FileOutputStream("c:/gbk.txt");
        //Create character output stream, transform stream, construct method, transfer byte output stream, and specify encoding table name
        OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk");
        //Write string
        osw.write("Hello");
 	 	//Refresh stream
        osw.flush();
        osw.close();
    }

7.2 InputStreamReader

InputStreamReader inherits Reader, character input stream, and reads text files

Byte flow is a bridge to character flow, and byte flow becomes character flow

  • Construction method:
    • InputStreamReader(InputStream out) passes an arbitrary byte input stream
    • InputStreamReader(InputStream out,String encoded table name) passes any byte input stream
    /**
     * Read GBK file
     */
    public static void readGBK() throws IOException{
        //Create byte stream object and bind data source
        FileInputStream fis = new FileInputStream("c:/gbk.txt");
        //Create the conversion stream object, bind the byte input stream, and specify the encoding table
        InputStreamReader isr = new InputStreamReader(fis,"GBK");
        //Read character array
        char[] chars = new char[1024];
        //Save the return value of the read method read
        int r = 0 ;
        r = isr.read(chars);
        //Convert array to string
        System.out.println(new String(chars,0,r));

        isr.close();
    }

    /**
     * Read UTF-8 file
     */
    public static void readUTF8()throws IOException {
        //Create byte stream object and bind data source
        FileInputStream fis = new FileInputStream("c:/utf.txt");
        //Create the conversion stream object and bind the byte input stream
        InputStreamReader isr = new InputStreamReader(fis);
        //Read character array
        char[] chars = new char[1024];
        //Save the return value of the read method read
        int r = 0 ;
        r = isr.read(chars);
        //Convert array to string
        System.out.println(new String(chars,0,r));

        isr.close();
    }

7.3 convenience

  • FileWriter inherits OutputStreamWriter
    • Is an output stream of characters written to a text file
    • Directly use the default coding table UTF-8
    • The FileWriter constructor can directly pass the file name of the string
public static void main(String[] args) throws IOException {
    //Create a convenient class for character output stream
    FileWriter fw = new FileWriter("day20/hehe.txt");
    //Write string
    fw.write("thank you");
    fw.close();
}
  • FileReader inherits InputStreamReader
    • Is the input stream of characters and reads the text file
    • Directly use the default coding table UTF-8
    • The FileReader constructor can directly pass the file name of the string
public static void main(String[] args)throws IOException {
    //Create character input stream object and bind data source
    FileReader  fr = new FileReader("day20/hehe.txt");
    //Read character array
    char[] chars = new char[1024];
    int r = 0;
    while ( (r = fr.read(chars)) !=-1){
        System.out.print(new String(chars,0,r));
    }
    fr.close();
}

7.4 buffer stream of character output stream

BufferedWriter: the buffered stream of character stream. It inherits the Writer and writes to a text file

-Special method: newLine() writes the text newline character, which is platform independent

  • Construction method: BufferedWriter(Writer w) can pass any character output stream
    /**
     * Buffer for character output stream, write newline
     */
    public static void write() throws IOException {
        //Create a convenient class for character output stream
        FileWriter fw = new FileWriter("day20/xixi.txt");
        //Create a buffer stream of character output stream and construct a method to transfer fw stream
        BufferedWriter bfw = new BufferedWriter(fw);
        bfw.write("first line");
        bfw.newLine();
        bfw.write("Second line");
        bfw.flush();
        bfw.close();
    }

7.5 buffered stream of character input stream

BufferedReader: the buffered stream of character stream. It inherits the Reader and reads text files

-Special method: String readLine() reads one line of text, which is platform independent

  • Construction method: BufferedReader (Reader r) can pass any character input stream
    /**
     * The buffer of the character input stream to read the text line
     */
    public static void read() throws IOException {
        //Create a convenient class for character input stream
        FileReader fr = new FileReader("day20/xixi.txt");
        //Creates a buffer stream object for the character input stream
        BufferedReader bfr = new BufferedReader(fr);
        //Define the string and save the read text line
        String line = null;
        while ( (line = bfr.readLine()) != null){
            System.out.println(line);
        }
        bfr.close();
    }

7.6 character stream copy text file

Incorrect application cannot guarantee that the copied file is consistent with the source file

8. Print stream

  • PrintStream: byte output stream
  • PrintWriter: character output stream
  • Print stream properties:
    • The print stream is responsible for printing and does not care about the data source
    • Convenient printing of various forms of data
    • The print stream will never throw an IOException
    • With automatic refresh
/**
* Print stream output, in the construction method of print stream, transfer stream (bytes, characters)
* Automatic refresh: write true for the second parameter of the construction method. The first parameter must be an IO stream object, not a string
* Call one of the three methods: println, printf and format to enable automatic refresh
*/
public static void print()throws IOException {
    //Convenience class
    FileWriter fw = new FileWriter("day20/print.txt");
    //Create print stream objects and pass convenience classes
    PrintWriter pw = new PrintWriter(fw,true);
    pw.println(1.5); //Easy to print and output as is
}

9. Basic data type flow

  • DataInputStream

    • Basic data type read stream
    • Construction method, passing byte input stream
  • DataOutputStream

    • Write stream of basic data type
    • Construction method to transfer byte output stream
 public static void main(String[] args) throws IOException {
        read();
    }
    /**
     * DataInputStream Read basic type
     * readInt() End of file read: EOFException thrown
     */
    public static void read()throws IOException{
        //Create a basic type input stream, and the constructor binds the byte input stream
        DataInputStream dis = new DataInputStream(new FileInputStream("day20/data.txt"));
        //Read basic type
        while (true) {
            try {
                int i = dis.readInt();
                System.out.println("i = " + i);
            }catch (IOException ex){
                //ex.printStackTrace();
                break;
            }
        }
        dis.close();
    }

    /**
     *  DataOutputStream Write basic type
     */
    public static void write()throws IOException {
        //Create basic data type output stream
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("day20/data.txt"));
        //Write basic data type
        dos.writeInt(6);
        dos.writeInt(16);
        dos.writeInt(26);
        dos.writeInt(-1);
        dos.writeInt(100);

        dos.close();
    }

10.File class

  • Folder Directory: a container for storing files. It is set to prevent duplicate names of files. Files are classified. The folder itself does not store any data. Calculating professional data is called directory

  • File: a file that stores data. File names in the same directory cannot be the same

  • Path: the location of a directory or file on disk

    • c:\jdk8\jar is the path to the directory and the path to a folder
    • c:\jdk8\bin\javac.exe is the path to the file
  • File class, an object that describes directory files and paths

  • Platform independence

10.1 construction method of file class

  • File (String pathname) passes the pathname of the string
  • File(String parent,String child) passes the parent path of the string and the child path of the string
  • File(File parent,String child) passes the parent path of file type and the child path of string
 public static void main(String[] args) {
        fileMethod03();
    }
    /**
     * File(File parent,String child)Pass the parent path of File type and the child path of string
     */
    public static void fileMethod03(){
        File parent = new File("C:/Java/jdk1.8.0_221");
        String child = "bin";
        File file = new File(parent,child);
        System.out.println(file);
    }

    /**
     * File(String parent,String child)Pass the parent path of the string and the child path of the string
     * C:\Java\jdk1.8.0_221\bin
     * C:\Java\jdk1.8.0_221 Yes C:\Java\jdk1.8.0_221\bin's parent path
     */
    public static void fileMethod02(){
        String parent = "C:/Java/jdk1.8.0_221";
        String child = "bin";
        File file = new File(parent,child);
        System.out.println(file);
    }

    /**
     * File (String pathname)Pass the pathname of the string
     */
    public static void fileMethod(){
        //The path to the string becomes a File object
        File file = new File("C:\\Java\\jdk1.8.0_221\\bin");
        System.out.println(file);
    }

10.2 creation method of file class

  • boolean createNewFile() creates a File, and the File path is written in the File construction method
  • boolean mkdirs() creates a directory. The location and name of the directory are written in the File construction method
    //Create folder / directory boolean mkdirs()
    public static void fileMethod02(){
        File file = new File("C://Java//1.txt");
        boolean b = file.mkdirs();
        System.out.println("b = " + b);
    }

    //Create file boolean createNewFile()
    public static void fileMethod() throws IOException {
        File file = new File("C://Java//1.txt");
        boolean b = file.createNewFile();
        System.out.println("b = " + b);
    }

10.3 deletion method of file class

  • boolean delete() deletes the specified directory or File. The path is written in the constructor of the File class
    • It will not enter the recycle bin and will be deleted directly from the disk, which is risky
    public static void fileMethod03(){
        File file = new File("C:/Java/aaa");
        boolean b = file.delete();
        System.out.println("b = " + b);
    }

10.4 File judgment method

  • boolean exists() determines whether the path in the construction method exists
  • boolean isDirectory() determines whether the path in the construction method is a folder
  • boolean isFile() determines whether the path in the construction method is a file
  • boolean isAbsolute() determines whether the path in the construction method is an absolute path

10.4.1 absolute path and relative path

  • Absolute path
    • The path in the disk is unique
    • In Windows system, the drive letter starts with C:/Java/jdk1.8.0_221/bin/javac.exe
    • Linux or Unix system, starting with /, disk root / usr/local
    • Internet path: www.baidu.com
      • https://item.jd.com/100007300763.html
      • https://pro.jd.com/mall/active/3WA2zN8wkwc9fL9TxAJXHh5Nj79u/index.html
  • Relative path
    • There must be a reference
    • C:/Java/jdk1.8.0_221/bin/javac.exe
    • bin is the reference point: parent path C: / Java / jdk1.8.0_ two hundred and twenty-one
    • bin is the reference point: sub path javac.exe
    • bin reference point: the parent path is represented by... /
    /**
     * boolean isAbsolute() Judge whether the path in the construction method is an absolute path
     * The path in absolute form is not written, and the path in relative form is written. It is under the current project path by default
     */
    public static void fileMethod04(){
        File file = new File("C:/Java/jdk1.8.0_221/bin/javac.exe");
        boolean b = file.isAbsolute();
        System.out.println("b = " + b);

        File file2 = new File("javac.exe");
        b = file2.isAbsolute();
        System.out.println("b = " + b);
    }

10.5 method of obtaining file class

  • File getAbsoluteFile() gets the absolute path, and the return value is file type
  • File getParentFile() gets the parent path, and the return value is file type
  • String getName() gets the name of the path in the File constructor
  • String getPath() gets the path in the File construction method, and the complete path is converted to string return
  • long length() gets the number of bytes of the file
/**
* File Class
* - File getAbsoluteFile() Get the absolute path, and the return value is File type
* - File getParentFile() Get the parent path, and the return value is File type
*/
public static void fileMethod02(){
    File file = new File("C:\\Java\\jdk1.8.0_221\\bin\\java.exe");
    //Get absolute path
    File absoluteFile = file.getAbsoluteFile();
    System.out.println("absoluteFile = " + absoluteFile);
    //Get parent path
    File parentFile = file.getParentFile().getParentFile();
    System.out.println("parentFile = " + parentFile);
    //Bytes of file
    long length = file.length();
    System.out.println("length = " + length);
}

/**
* File Class acquisition method
* - String getName() Gets the name of the path in the File constructor
* - String getPath() Get the path in the File construction method, and convert the complete path into a String to return
*/
public static void fileMethod(){
    File file = new File("C:\\Java\\jdk1.8.0_221\\bin\\java.exe");
    //getName() get name
    String name = file.getName();
    System.out.println("name = " + name);

    //getPath() constructs method parameters and converts them into strings
    String path = file.getPath();
    System.out.println("path = " + path);
}

10.6 method listFiles() of file class

The return value is the File [] array, which stores multiple File objects. The function of the method is to traverse the current folder

    public static void main(String[] args) {
        //fileMethod();

     foreachDir(new File("D:\\study\\graduate student\\first year graduated school student\\self-taught\\Java study\\MarkDown"));
        foreachDirs(new File("D:\\study"));
    /**
     * Recursive traversal of the directory: pass the parameters, which path to traverse, and pass it
     */
    public static void foreachDir(File dir){
        System.out.println(dir);
        //listFiles() traverses the directory C: \ Java \ jdk1.8.0_ two hundred and twenty-one
        File[] files = dir.listFiles();
        //Traverse the array and take out the File object in the array
        //Is the full path (absolute path) of all files traversed
        for(File f : files){
            //Determine whether the traversed path is a folder
            if(f.isDirectory()) //C:\Java\jdk1.8.0_221\jre, enter to continue traversal
                //Call yourself recursively and pass the path
                foreachDir(f);
            else
                System.out.println(f);
        }
    }

    /**
     * Traverse directory
     */
   //    Traverse directory
    public static void foreachDirs(File file){
        File[] files=file.listFiles();
        for (File file1 : files) {
            System.out.println(file1);
        }
    }
    //No parameter
    public static void foreachDirs(){
        File    file=new File("D:\\study");
        File[] files=file.listFiles();
        for (File file1 : files) {
            System.out.println(file1);
        }
    }
    
}

Posted by bhavin_85 on Sun, 28 Nov 2021 05:24:33 -0800