day23_FIle class, byte stream, byte buffer stream

Posted by creativeimpact on Fri, 10 Sep 2021 00:37:56 +0200

File class  

  • The File class represents platform independent files and directories under the java.io package, that is, if you want to operate files and directories in the program, you can use the File class to create, delete and rename files and directories.
  • In the API, File is interpreted as an abstract representation of File and directory pathnames, that is, the File class is the path of a File or directory, not the File itself. Therefore, the File class cannot directly access the File content itself. If you need to access the File content itself, you need to use the input / output stream. The File object is like the "route address" to the reservoir. To "access" the water to your "home", you need a "pipe".
  • For File, what it encapsulates is not a real File, but just a path name. It can exist or not exist. In the future, the content of this path will be converted into a specific existence through specific operations

Construction method of File class

  Code example

package demo01;

import java.io.File;

public class Demo01 {
    public static void main(String[] args) {
        //File(String pathname): create a new file instance by converting the given pathname string to an abstract pathname
        File f1 = new File("D:\\java.txt");
        System.out.println(f1); //D:\java.txt

        //File(String parent, String child): creates a new file instance from the parent pathname string and the child pathname string
        File f2 = new File("D:\\", "java.txt");
        System.out.println(f2); //D:\java.txt

        //File(File parent, String child): creates a new file instance from the parent abstract pathname and child pathname strings
        File f3 = new File("D:\\");
        File f4 = new File(f3, "java.txt");
        System.out.println(f4); //D:\java.txt

    }
}

Tips:

  • A File object represents a File or directory that actually exists in the hard disk.
  • Whether a File or directory exists in this path does not affect the creation of the File object.

Absolute path and relative path

  • Absolute path: it is a complete path, starting from the drive letter
  • Relative path: a simplified path, relative to the path under the current project

Code example

package demo01;

import java.io.File;

public class Demo01 {
    public static void main(String[] args) {
        // Absolute path: it is a complete path, starting from the drive letter
        File file1 = new File("D:\\a.txt");

        //Relative path: a simplified path, starting from the root directory of the current project
        File file2 = new File("a.txt");
        File file3 = new File("Module name\\a.txt");
    }
}

File class creation function

public boolean createNewFile(): when the file with this name does not exist, create a new empty file named by the abstract pathname

package demo01;

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

public class Demo01 {
    public static void main(String[] args) throws IOException {
        // Absolute path: it is a complete path, starting from the drive letter
        File file = new File("D:\\a.txt");
        /*
        public boolean createNewFile()    Create a new empty file
        Note:
          1.If the file exists, the creation fails and returns false
          2.If the file does not exist, the creation succeeds and returns true
          3.createNewFile Method can only create files regardless of whether the caller has a suffix or not
         */
        boolean result = file.createNewFile();
        System.out.println(result);

    }
}

  public boolean mkdir( ) :   Creating a single level folder is not recommended

package demo01;

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

public class Demo01 {
    public static void main(String[] args) throws IOException {
        // Current path: start from the root directory of the current project
        File file = new File("a.txt");
        /*
         public boolean mkdir()    Create a single level folder
          Note:
             1.You can only create single level folders, not multi-level folders
             2.Only single level folders can be created regardless of whether the caller has a suffix or not
             3.If the folder does not exist, true will be returned if it is created, and false if it does not exist
        */
        boolean mkdir = file.mkdir();
        System.out.println(mkdir);

    }
}

  public boolean mkdirs(): create a directory named by this abstract pathname, including any required but nonexistent parent directory. Recommended use

package demo01;

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

public class Demo01 {
    public static void main(String[] args) throws IOException {
        // Current path: start from the root directory of the current project
        File file = new File("123\\456");
        /*
        public boolean mkdirs()           Create a multi-level folder
          Note:
              1.You can create single level folders or multi-level folders
              2.Only folders can be created regardless of whether the caller has a suffix or not
              3.If it exists, the creation fails and returns false. If it does not exist, the creation succeeds and returns true
        */
        boolean mkdir = file.mkdirs();
        System.out.println(mkdir);

    }
}

File class deletion function

public boolean delete(): deletes the file or directory represented by this abstract pathname

package demo01;

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

public class Demo01 {
    public static void main(String[] args) throws IOException {
        // Current path: start from the root directory of the current project
        File file = new File("a.txt");
        /*
        Note:
        1.Delete items that do not go to the recycle bin
        2.If you delete a file, you can delete it directly. If you delete a folder, you can delete an empty folder
        3.If you want to delete a folder with content, you can only enter the folder and delete all the contents before deleting the folder again
        Simply put: only files and empty folders can be deleted
        */
        boolean result = file.delete();
        System.out.println(result);

    }
}

File class judgment function

  • public boolean exists(): whether the File or directory represented by this File actually exists.
  • public boolean isDirectory(): whether this File indicates a directory.
  • public boolean isFile(): this File indicates whether it is a File.
package demo01;

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

public class Demo01 {
    public static void main(String[] args) throws IOException {
        // Current path: start from the root directory of the current project
        File file = new File("a.txt");
        //  exists(): whether the File or directory represented by this File actually exists.
        boolean exists = file.exists();

        // isFile() `: this File indicates whether it is a File.
        boolean result1 = file.isFile();

        // isDirectory() `: this File indicates whether it is a directory.
        boolean result2 = file.isDirectory();

        System.out.println(exists);// true
        System.out.println(result1);//true
        System.out.println(result2);//false

    }
}

  If the file or directory does not exist, exists(), isFile(), and isDirectory() return false

File class get function

  • public String getName(): returns the name of the File or directory represented by this File.

  Code example

package demo01;

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

public class Demo01 {
    public static void main(String[] args) throws IOException {
        File f = new File("d:/aaa/bbb.txt");
        File f2 = new File("d:/aaa");
        /*
        getName() : Returns the name of the File or directory represented by this File.
                   If the caller is a file, the file name and suffix are obtained
                   If the caller is a folder, the name of the folder is obtained
         */
        System.out.println("File name:" + f.getName());//File name: bbb.txt
        System.out.println("Directory name:" + f2.getName());//Directory name: aaa

    }
}

Public File [] listfiles(): returns the File object array of files and directories in the directory represented by this abstract pathname

package demo01;

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

public class Demo01 {
    public static void main(String[] args) throws IOException {
        // Current path: start from the root directory of the current project
        File file = new File("D:\\");
        //Enter the folder, get all the files in the folder and the File objects of the folder, and return these File objects in an array
        File[] files = file.listFiles();
        for (File f : files) {
            System.out.println(f);
        }


    }
}

  Requirement: create an a.txt file in the aaa folder under the current module

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

//Create an a.txt file in the aaa folder under the current module
public class Demo01 {
    public static void main(String[] args) throws IOException {
        //1. Create a File object and point to the aaa folder
        File file = new File("Demo\\aaa");
        //2. Judge whether the aaa folder exists. If it does not exist, create it
        if (!file.exists()) {
            //If the folder does not exist, it is created
            file.mkdirs();
        }
        //3. Create a File object and point to the a.txt File in the aaa folder
        File file1 = new File(file, "a.txt");
        //4. Create this file
        file1.createNewFile();
        
    }
}

  Requirement: delete a multi-level folder

import java.io.File;
public class Demo01 {
    public static void main(String[] args) {
        File src = new File("C:\\apple\\Desktop\\src");
        deleteDir(src);
    }

    //1. Define a method to receive a File object
    private static void deleteDir(File src) {
        //2. Traverse the File object and get each File and folder object below it
        File[] files = src.listFiles();
        //3. Judge whether the File object currently traversed is a File or a folder
        for (File file : files) {
            //4. If it is a file, delete it directly
            if (file.isFile()) {
                file.delete();
            } else {
                //5. If it is a folder, call yourself recursively and pass the File object currently traversed as a parameter
                deleteDir(file);//The parameter must be a File object in the src folder
            }
        }
        //6. The folder File object passed by the parameter has been processed. Finally, delete the empty folder directly
        src.delete();
    }
}

Requirement: count the number of files in a folder

import java.io.File;
import java.util.HashMap;

public class Demo02 {
    public static void main(String[] args) {
        //Count the number of times each file appears in a folder
        //Statistics --- define a variable for statistics. -- disadvantage: only one file can be counted at the same time
        //Use the map set for data statistics, key - file suffix value - times

        File file = new File("Demo");
        HashMap<String, Integer> hm = new HashMap<>();
        getCount(hm, file);
        System.out.println(hm);
    }

    //1. Define a method. The parameter is the HashMap set used to count the times and the folder to be counted by the File object
    private static void getCount(HashMap<String, Integer> hm, File file) {
        //2. Traverse the File object and get each File and folder object below it
        File[] files = file.listFiles();
        for (File f : files) {
            //3. Judge whether the current File object is a File or a folder
            if (f.isFile()) {
                //If it is a file, judge whether the suffix of this type of file has appeared in the HashMap collection
                String fileName = f.getName();
                String[] fileNameArr = fileName.split("\\.");
                if (fileNameArr.length == 2) {
                    String fileEndName = fileNameArr[1];
                    if (hm.containsKey(fileEndName)) {
                        //If yes, get the number of times the suffix name of this type of file appears. For it, + 1 is saved back to the collection
                        Integer count = hm.get(fileEndName);
                        //This kind of document appeared again
                        count++;
                        //Overwrite the number of occurrences
                        hm.put(fileEndName, count);
                    } else {
                        // No, save the suffix of this type of file into the collection for 1 times
                        hm.put(fileEndName, 1);
                    }
                }
            } else {
                //If it is a folder, call yourself recursively, the HashMap set is the parameter set, and the File object is the code implementation of the current folder object
                getCount(hm, f);
            }
        }
    }
}

IO stream

  • We can regard data transmission as a kind of data flow. According to the flow direction and based on memory, it is divided into input input and output, that is, the flow to memory is the input flow and the output flow out of memory.
  • I/O operation in Java mainly refers to the use of the contents under the java.io package for input and output operations. Input is also called read data, and output is also called write data.
  • The essence of stream is data transmission. IO stream is used to deal with data transmission between devices. Common applications: file replication; File upload; File download

Classification of IO

According to the flow direction of data, it is divided into input flow and output flow.

  • Input stream: a stream that reads data from other devices into memory. End with InputStream,Reader
  • Output stream: a stream that writes data out of memory to other devices. End with OutputStream, Writer

According to the type of data, it is divided into byte stream and character stream.

  • Byte stream: a stream that reads and writes data in bytes. Ends with InputStream and OutputStream
  • Character stream: a stream that reads and writes data in character units. End with Reader and Writer

Usage scenarios of IO streams

  • If the operation is a plain text file, the character stream is preferred. You can use the built-in TXT to open it, and the read files are plain text files
  • If binary files such as picture, video and audio are operated, byte stream is preferred
  • If the file type is uncertain, byte stream is preferred. Byte stream is a universal stream

Top 4 Abstract superclasses

All file data (text, pictures, videos, etc.) are stored in binary numbers, bytes by bytes, and the same is true during transmission. Therefore, byte stream can transfer any file data. When operating a stream, we should always make it clear that no matter what kind of stream object is used, the underlying transmission is always binary data.  

Byte output stream OutputStream

The java.io.OutputStream abstract class is a superclass that represents all classes of byte output stream and writes the specified byte information to the destination. It defines the basic common function method of byte output stream.

  • public void close(): close this output stream and release any system resources associated with this stream.
  • public void flush(): flushes this output stream and forces any buffered output bytes to be written out.
  • public void write(byte[] b): writes b.length bytes from the specified byte array to this output stream.
  • public void write(byte[] b, int off, int len): writes len bytes from the specified byte array and outputs them to this output stream starting from offset off.
  • public abstract void write(int b): outputs the specified bytes to the stream.

FileOutputStream class

OutputStream has many subclasses. Let's start with the simplest subclass. The java.io.FileOutputStream class is a file output stream used to write data out to a file.

To write data using a byte output stream

  1. Create a byte output stream object (call the system function to create a file, create a byte output stream object, and let the byte output stream object point to the file)
  2. Call the write data method of byte output stream object
  3. Free resources (close this file output stream and free any system resources associated with this stream)

Write out a single byte. The write(int b) method can write out one byte of data at a time. The code usage demonstration:

import java.io.FileOutputStream;
import java.io.IOException;

public class Demo01 {
    public static void main(String[] args) throws IOException {

        // Create a stream object using the file name - tell the virtual machine which file I want to write data to
        //If the file does not exist, it will be created automatically for us. If the file exists, it will be emptied
        FileOutputStream fos = new FileOutputStream("fos.txt");

        // When writing data and passing an integer, what is actually written to the file is the character corresponding to the integer in the code table
        fos.write(97); // Write the first byte
        fos.write(98); // Write the second byte
        fos.write(99); // Write the third byte

        // close resource
        fos.close(); //Tell the operating system that I don't want to use this file anymore
    }
}

Write out byte array: write(byte[] b). You can write out the data in the array each time. The code usage demonstration:

import java.io.FileOutputStream;
import java.io.IOException;

public class Demo01 {
    public static void main(String[] args) throws IOException {
        // Create a stream object with a file name
        FileOutputStream fos = new FileOutputStream("fos.txt");
        // Convert string to byte array
        byte[] b = "ate".getBytes();
        // Write out byte array data
        fos.write(b);
        // close resource
        fos.close();
    }
}

Write out the byte array of the specified length: write(byte[] b, int off, int len). Each write starts from the off index, len bytes. Code usage demonstration:

import java.io.FileOutputStream;
import java.io.IOException;

public class Demo01 {
    public static void main(String[] args) throws IOException {
        // Create a stream object with a file name
        FileOutputStream fos = new FileOutputStream("fos.txt");
        // Convert string to byte array
        byte[] b = "abcdefg".getBytes();
        // Write 3 bytes starting with index 2. Index 2 is c, two bytes, that is, cde.
        fos.write(b,2,3);
        // close resource
        fos.close();
    }
}

Data append and continue

After the above demonstration, each time the program runs and creates an output stream object, the data in the target file will be cleared. How to keep the data in the target file and continue to add new data?

  • Public fileoutputstream (File, Boolean append): creates a File output stream to write to the File represented by the specified File object.
  • public FileOutputStream(String name, boolean append): creates a file output stream and writes it to the file with the specified name.

For these two construction methods, a boolean value needs to be passed in the parameters. true means to append data, and false means to empty the original data. The output stream object created in this way can specify whether to append or renew

Carriage returns \ r and line breaks \ n:

  • Carriage return: return to the beginning of a line.
  • newline: next line.

Line breaks in the system:

  • In Windows system, the end of each line is enter + line feed, that is \ r\n;
  • In Unix systems, there is only newline at the end of each line, that is \ n;
  • On the MAC system, the end of each line is enter, that is, \ r. Unified with Linux starting with Mac OS X.

Code usage demonstration:

import java.io.FileOutputStream;
import java.io.IOException;

public class Demo01 {
    public static void main(String[] args) throws IOException {
        // Create a stream object using the file name and append the data
        FileOutputStream fos = new FileOutputStream("fos.txt",true);
        // Define byte array
        byte[] words = {97, 98, 99, 100, 101};
        // Traversal array
        for (int i = 0; i < words.length; i++) {
            // Write a byte
            fos.write(words[i]);
            // Write a newline and convert the newline symbol into an array
            fos.write("\r\n".getBytes());
        }
        // close resource
        fos.close();
    }
}

Byte stream write data plus exception handling

Sample code

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Demo02 {
    public static void main(String[] args) {
        FileOutputStream fos = null;//Improve scope
        try {//Possible exception codes
            fos = new FileOutputStream("test.txt");
            byte[] bytes = "having dinner".getBytes();
            fos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {//If it is judged that it is not null, it will be closed; otherwise, null exception will occur
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}

Byte input stream InputStream

The java.io.InputStream abstract class is a superclass representing all classes of byte input stream, which can read byte information into memory. It defines the basic common function method of byte input stream.

  • public void close(): close this input stream and release any system resources associated with this stream.
  • public abstract int read(): reads the next byte of data from the input stream.
  • public int read(byte[] b): read some bytes from the input stream and store them in byte array B.

FileInputStream class

The java.io.FileInputStream class is a file input stream that reads bytes from a file. It is a subclass of InputStream

To read data from a byte input stream

  1. Create byte input stream object
  2. Call the read data method of byte input stream object
  3. Release resources

Read single byte: the read method can read one byte of data at a time, promote it to int type, read it to the end of the file, and return - 1. Code usage demonstration:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Demo02 {
    public static void main(String[] args) throws IOException {
        /*
        If the file exists, no error will be reported
        If the file does not exist, an error will be reported directly
        */
        FileInputStream fis = new FileInputStream("a.txt");

        /*
        Read one byte at a time, and the return value is the byte data read this time
        That is, the number corresponding to the character in the code table
         */
        int read = fis.read();

        //If we want to see character data, we must forcibly convert it to char
        System.out.println((char) read);

        //Release resources
        fis.close();

    }
}

Loop to improve the reading mode, read data, and demonstrate the use of code:

import java.io.FileInputStream;
import java.io.IOException;

public class Demo02 {
    public static void main(String[] args) throws IOException {
        /*
        If the file exists, no error will be reported
        If the file does not exist, an error will be reported directly
        */
        FileInputStream fis = new FileInputStream("a.txt");

        /*
        Read one byte at a time, and the return value is the byte data read this time
        That is, the number corresponding to the character in the code table
         */
        int b;// Save read data
        // Cyclic reading
        while ((b = fis.read()) != -1) {
            //If we want to see character data, we must forcibly convert it to char
            System.out.println((char) b);
        }

        //Release resources
        fis.close();

    }
}

Read using byte array: read(byte[] b). Each time the length of B is read into the array, return the number of valid bytes read. When reading to the end, return - 1  , Code usage demonstration:

import java.io.FileInputStream;
import java.io.IOException;

public class Demo02 {
    public static void main(String[] args) throws IOException {
            // Create a stream object with a file name
            FileInputStream fis = new FileInputStream("test.txt");
            // Define variables as valid numbers
            int len;
            // Defines a byte array as a container for byte data
            byte[] b = new byte[1024];
            // Cyclic reading
            while (( len= fis.read(b))!=-1) {
                // After each reading, the valid byte part of the array is changed into a string for printing
                System.out.println(new String(b,0,len));//  len number of valid bytes read each time
            }
            // close resource
            fis.close();

    }
}

Byte buffer stream

In order to improve the efficiency of operating data, buffer stream came into being

  • BufferOutputStream: this class implements buffered output stream. By setting such output stream, an application can write bytes to the underlying output stream without causing calls to the underlying system for each byte written
  • BufferedInputStream: creating BufferedInputStream will create an internal buffer array. When bytes are read or skipped from the stream, the internal buffer will be refilled from the contained input stream as needed, many bytes at a time

Construction method:

Byte buffered stream copy video

  1. Create byte input stream object from data source
  2. Create byte output stream object based on destination
  3. Read and write data, copy video
  4. Release resources

  Code example

import java.io.*;

public class CopyAviDemo {
    public static void main(String[] args) throws IOException {

        //Copy video
        method2();

    }

    //The byte buffer stream reads and writes one byte array at a time
    public static void method2() throws IOException {
        //Create a byte buffered input stream
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\1.vep"));
        //Create a byte buffered output stream
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C:\\Byte stream copy picture.vep"));
        //Create a container for storing data
        byte[] bys = new byte[1024];
        // Define variables as valid numbers
        int len;
        // Cyclic reading
        while ((len = bis.read(bys)) != -1) {
            // After each reading, write the valid byte part of the array to the specified position
            bos.write(bys, 0, len);
        }

        bos.close();
        bis.close();
    }

}

Topics: Java