(20) [Io stream] File class, byte stream, byte buffer stream;

1.File class

1.1 File class overview and construction method [Application]

  • File class introduction

    • It is an abstract representation of file and directory pathnames
    • Files and directories can be encapsulated into objects through File
    • For File, what it encapsulates is not a real file, but just a path name. It may exist or not. In the future, the content of this path will be converted into specific existence
  • Constructor of the File class

    method nameillustrate
    File(String pathname)Creates a new File instance by converting the given pathname string to an abstract pathname
    File(String parent, String child)Creates a new File instance from the parent pathname string and the child pathname string
    File(File parent, String child)Creates a new File instance from the parent abstract pathname and the child pathname string
  • sample code

    public class FileDemo01 {
        public static void main(String[] args) {
            //File(String pathname): Creates a new File instance by converting the given pathname string to an abstract pathname
            File f1 = new File("E:\\itcast\\java.txt");
            System.out.println(f1);
    
            //File(String parent, String child): Creates a new File instance from the parent pathname string and the child pathname string
            File f2 = new File("E:\\itcast","java.txt");
            System.out.println(f2);
    
            //File(File parent, String child): Creates a new File instance from the parent abstract pathname and the child pathname string
            File f3 = new File("E:\\itcast");
            File f4 = new File(f3,"java.txt");
            System.out.println(f4);
        }
    }
    

1.2 Absolute path and relative path [Understanding]

  • absolute path

    Is a complete path, starting from the drive letter

  • relative path

    Is a simplified path, relative to the path under the current project

  • sample code

    public class FileDemo02 {
        public static void main(String[] args) {
            // Is a complete path, starting from the drive letter
            File file1 = new File("D:\\itheima\\a.txt");
    
            // is a simplified path starting from the current project root directory
            File file2 = new File("a.txt");
            File file3 = new File("module name\\a.txt");
        }
    }
    

1.3File class creation function [Application]

  • Method classification

    method nameillustrate
    public boolean createNewFile()Creates a new empty file named by this abstract pathname when a file with that name does not exist
    public boolean mkdir()Create a directory named by this abstract pathname
    public boolean mkdirs()Create a directory named by this abstract pathname, including any required but non-existing parent directories
  • sample code

    public class FileDemo02 {
        public static void main(String[] args) throws IOException {
            //Requirement 1: I want to create a file java.txt in the E:\itcast directory
            File f1 = new File("E:\\itcast\\java.txt");
            System.out.println(f1.createNewFile());
            System.out.println("--------");
    
            //Requirement 2: I want to create a directory JavaSE under the E:\itcast directory
            File f2 = new File("E:\\itcast\\JavaSE");
            System.out.println(f2.mkdir());
            System.out.println("--------");
    
            //Requirement 3: I want to create a multi-level directory JavaWEB\HTML under the E:\itcast directory
            File f3 = new File("E:\\itcast\\JavaWEB\\HTML");
    //        System.out.println(f3.mkdir());
            System.out.println(f3.mkdirs());
            System.out.println("--------");
    
            //Requirement 4: I want to create a file javase.txt in the E:\itcast directory
            File f4 = new File("E:\\itcast\\javase.txt");
    //        System.out.println(f4.mkdir());
            System.out.println(f4.createNewFile());
        }
    }
    

1.4 File class delete function [Application]

  • Method classification

    method nameillustrate
    public boolean delete()delete the file or directory denoted by this abstract pathname
  • sample code

    public class FileDemo03 {
        public static void main(String[] args) throws IOException {
    //        File f1 = new File("E:\\itcast\\java.txt");
            //Requirement 1: Create a java.txt file in the current module directory
            File f1 = new File("myFile\\java.txt");
    //        System.out.println(f1.createNewFile());
    
            //Requirement 2: Delete the java.txt file in the current module directory
            System.out.println(f1.delete());
            System.out.println("--------");
    
            //Requirement 3: Create an itcast directory under the current module directory
            File f2 = new File("myFile\\itcast");
    //        System.out.println(f2.mkdir());
    
            //Requirement 4: Delete the itcast directory under the current module directory
            System.out.println(f2.delete());
            System.out.println("--------");
    
            //Requirement 5: Create a directory itcast under the current module, and then create a file java.txt in this directory
            File f3 = new File("myFile\\itcast");
    //        System.out.println(f3.mkdir());
            File f4 = new File("myFile\\itcast\\java.txt");
    //        System.out.println(f4.createNewFile());
    
            //Requirement 6: Delete the directory itcast under the current module
            System.out.println(f4.delete());
            System.out.println(f3.delete());
        }
    }
    

1.5 File class judgment and acquisition function [Application]

  • judgment function

    method nameillustrate
    public boolean isDirectory()Tests whether the File denoted by this abstract pathname is a directory
    public boolean isFile()Tests whether the File denoted by this abstract pathname is a file
    public boolean exists()Tests whether the File denoted by this abstract pathname exists
  • get function

    method nameillustrate
    public String getAbsolutePath()Returns the absolute pathname string for this abstract pathname
    public String getPath()converts this abstract pathname to a pathname string
    public String getName()Returns the name of the file or directory denoted by this abstract pathname
    public File[] listFiles()Returns an array of File objects for the files and directories in the directory denoted by this abstract pathname
  • sample code

    public class FileDemo04 {
        public static void main(String[] args) {
            //Create a File object
            File f = new File("myFile\\java.txt");
    
    //        public boolean isDirectory(): Tests whether the File represented by this abstract pathname is a directory
    //        public boolean isFile(): Tests whether the File represented by this abstract pathname is a file
    //        public boolean exists(): Test whether the File represented by this abstract pathname exists
            System.out.println(f.isDirectory());
            System.out.println(f.isFile());
            System.out.println(f.exists());
    
    //        public String getAbsolutePath(): returns the absolute pathname string of this abstract pathname
    //        public String getPath(): converts this abstract pathname to a pathname string
    //        public String getName(): Returns the name of the file or directory denoted by this abstract pathname
            System.out.println(f.getAbsolutePath());
            System.out.println(f.getPath());
            System.out.println(f.getName());
            System.out.println("--------");
    
    //        public File[] listFiles(): Returns an array of File objects for the files and directories in the directory represented by this abstract pathname
            File f2 = new File("E:\\itcast");
            File[] fileArray = f2.listFiles();
            for(File file : fileArray) {
    //            System.out.println(file);
    //            System.out.println(file.getName());
                if(file.isFile()) {
                    System.out.println(file.getName());
                }
            }
        }
    }
    

1.6 File Class Exercise 1 [Application]

  • case requirements

    Create an a.txt file in the aaa folder under the current module

  • Implementation steps

    • Create a File object, pointing to the aaa folder
    • Determine whether the aaa folder exists, and create it if it does not exist
    • Create a File object, pointing to the a.txt file under the aaa folder
    • create this file
  • Code

    public class Test1 {
        public static void main(String[] args) throws IOException {
            //Exercise 1: Create an a.txt file in the aaa folder under the current module
           /* File file = new File("filemodule\\aaa\\a.txt");
            file.createNewFile();*/
            //Note: The folder where the file is located must exist.
    
          	//1. Create a File object and point to the aaa folder
            File file = new File("filemodule\\aaa");
          	//2. Determine whether the aaa folder exists, and create it if it does not exist
            if(!file.exists()){
                //If the folder does not exist, create it
                file.mkdirs();
            }
          	//3. Create a File object, pointing to the a.txt file under the aaa folder
            File newFile = new File(file,"a.txt");
          	//4. Create this file
            newFile.createNewFile();
        }
    }
    

1.7 File Class Exercise II [Application]

  • case requirements

    Delete a multi-level folder

  • Implementation steps

    • Define a method that receives a File object
    • Traverse the File object and get each file and folder object under it
    • Determine whether the currently traversed File object is a file or a folder
    • If it is a file, delete it directly
    • If it is a folder, call itself recursively, and pass the currently traversed File object as a parameter
    • The File object of the folder passed by the parameter has been processed, and finally delete the empty folder directly
  • Code

    public class Test2 {
        public static void main(String[] args) {
            //Exercise 2: Delete a multi-level folder
            //delete method
            //Only files and empty folders can be deleted.
            //If you want to delete a folder with content now?
            //First delete all the contents of this folder.
            //Finally delete this folder
    
            File src = new File("C:\\Users\\apple\\Desktop\\src");
            deleteDir(src);
        }
      
    	//1. Define a method to receive a File object
        private static void deleteDir(File src) {
            //First delete all the contents of this folder.
            //A recursive method calls itself within the method body.
            //NOTE: All folders and recursive combinations can be solved
            //2. Traverse the File object and get each file and folder object under it
            File[] files = src.listFiles();
            //3. Determine whether the currently traversed File object 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 itself recursively, and pass the currently traversed File object as a parameter
                    deleteDir(file);//The parameter must be the folder File object in the src folder
                }
            }
            //6. The folder File object passed by the parameter has been processed, and finally delete the empty folder directly
            src.delete();
        }
    
    }
    

1.8 File Class Exercise 3 [Application]

  • case requirements

    Count and print the number of each type of file in a folder

    The print format is as follows:

      		txt:3 indivual
      
      		doc:4 indivual
      
      		jpg:6 indivual
      
      		 ...
    
  • Implementation steps

    • Define a method, the parameter is the HashMap collection used to count the number of times and the folder to be counted by the File object
    • Traverse the File object and get every file and folder object under it
    • Determine whether the current File object is a file or a folder
    • If it is a file, determine whether the suffix of this type of file has appeared in the HashMap collection
      • Never appeared before, store the suffix name of this type of file in the collection, the number of times is 1
      • Appeared, get the number of occurrences of the suffix name of this type of file, add 1 to it, and save it in the collection
    • If it is a folder, recursively call itself, the HashMap collection is the parameter collection, and the File object is the current folder object
  • Code

    public class Test3 {
        public static void main(String[] args) {
            //Count the number of occurrences of each file in a folder.
            //Statistics --- Define a variable for statistics. ---- Disadvantage: Only one kind of file can be counted at the same time
            //Use the map collection for data statistics, key --- file suffix name value ---- times
    
            File file = new File("filemodule");
            HashMap<String, Integer> hm = new HashMap<>();
            getCount(hm, file);
            System.out.println(hm);
        }
      
    	//1. Define a method, the parameter is the HashMap collection used to count the number of 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 every file and folder object under it
            File[] files = file.listFiles();
            for (File f : files) {
              	//3. Determine whether the current File object is a file or a folder
                if(f.isFile()){
                  	//If it is a file, determine 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)){
                            //Appeared, get the number of occurrences of the suffix name of this type of file, add 1 to it, and save it in the collection
                            Integer count = hm.get(fileEndName);
                            //This file appeared again.
                            count++;
                            //Overwrite any existing occurrences.
                            hm.put(fileEndName,count);
                        }else{
                            // Never appeared before, store the suffix name of this type of file in the collection, the number of times is 1
                            hm.put(fileEndName,1);
                        }
                    }
                }else{
                  //If it is a folder, call itself recursively, the HashMap collection is the parameter collection, and the File object is the current folder object code implementation
                    getCount(hm,f);
                }
            }
        }
      
    }
    

2. Byte stream

2.1 Overview and classification of IO stream [Understanding]

  • Introduction to IO stream
    • IO: input/output (Input/Output)
    • Flow: It is an abstract concept and a general term for data transmission. That is to say, the transmission of data between devices is called flow, and the essence of flow is data transmission
    • IO flow is used to deal with data transmission between devices. Common applications: file copy; file upload; file download
  • Classification of IO streams
    • According to the flow of data
      • Input stream: read data
      • Output stream: write data
    • According to data type
      • byte stream
        • byte input stream
        • byte output stream
      • character stream
        • character input stream
        • character output stream
  • Usage scenarios of IO stream
    • If the operation is a plain text file, the character stream is preferred
    • If you are operating binary files such as pictures, videos, audios, etc., byte streams are preferred
    • If you are not sure about the file type, use byte stream first. Byte stream is a universal stream

2.2 Write data by byte stream [Application]

  • byte stream abstract base class

    • InputStream: This abstract class is the superclass of all classes that represent byte input streams
    • OutputStream: This abstract class is the superclass of all classes that represent byte output streams
    • Features of subclass names: subclass names are suffixed with the parent class name as the subclass name
  • byte output stream

    • FileOutputStream(String name): Create a file output stream to write to the file with the specified name
  • Steps to Write Data Using a Byte Output Stream

    • 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)
    • Call the write data method of the byte output stream object
    • free resources (closes this file output stream and frees any system resources associated with this stream)
  • sample code

    public class FileOutputStreamDemo01 {
        public static void main(String[] args) throws IOException {
            //Create a byte output stream object
          	/*
          		be careful:
          				1.If the file does not exist, it will be created for us
          				2.If the file exists, the file will be emptied
          	*/
          	//FileOutputStream(String name): Create a file output stream to write to the file with the specified name
            FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt");
    
            //void write(int b): write the specified byte to this file output stream
            fos.write(97);
    //        fos.write(57);
    //        fos.write(55);
    
            //Finally, resources must be released
            //void close(): Closes this file output stream and releases any system resources associated with this stream.
            fos.close();
        }
    }
    

2.3 Three ways to write data in byte stream [Application]

  • Classification of methods for writing data

    method nameillustrate
    void write(int b)Writes the specified bytes to this file output stream, writing data one byte at a time
    void write(byte[] b)Writes b.length bytes from the specified byte array to this file output stream one byte array data at a time
    void write(byte[] b, int off, int len)Writes len bytes from the specified byte array, starting at offset off, to this file output stream. Writes part of the data one byte array at a time
  • sample code

    public class FileOutputStreamDemo02 {
        public static void main(String[] args) throws IOException {
            //FileOutputStream(String name): Create a file output stream to write to the file with the specified name
            FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt");
            //FileOutputStream(File file): Creates a file output stream to write to the file represented by the specified File object
    //        FileOutputStream fos = new FileOutputStream(new File("myByteStream\\fos.txt"));
    
            //void write(int b): write the specified byte to this file output stream
    //        fos.write(97);
    //        fos.write(98);
    //        fos.write(99);
    //        fos.write(100);
    //        fos.write(101);
    
    //        void write(byte[] b): Writes b.length bytes from the specified byte array to this file output stream
    //        byte[] bys = {97, 98, 99, 100, 101};
            //byte[] getBytes(): returns the byte array corresponding to the string
            byte[] bys = "abcde".getBytes();
    //        fos.write(bys);
    
            //void write(byte[] b, int off, int len): Write len bytes starting from the specified byte array and writing this file output stream from offset off
    //        fos.write(bys,0,bys.length);
            fos.write(bys,1,3);
    
            //release resources
            fos.close();
        }
    }
    

2.4 Two small problems in writing data by byte stream [Application]

  • How to write data in byte stream to achieve line break

    • windows:\r\n
    • linux:\n
    • mac:\r
  • How to write data in byte stream to implement additional writing

    • public FileOutputStream(String name,boolean append)
    • Create a file output stream to write to a file with the specified name. If the second parameter is true, the bytes will be written to the end of the file instead of the beginning
  • sample code

    public class FileOutputStreamDemo03 {
        public static void main(String[] args) throws IOException {
            //Create a byte output stream object
    //        FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt");
            FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt",true);
    
            //write data
            for (int i = 0; i < 10; i++) {
                fos.write("hello".getBytes());
                fos.write("\r\n".getBytes());
            }
    
            //release resources
            fos.close();
        }
    }
    

2.5 byte stream write data plus exception handling [Application]

  • exception handling format

    • try-catch-finally

      try{
      	Code that may throw exceptions;
      }catch(exception class name variable name){
      	exception handling code;
      }finally{
      	Perform all cleanup operations;
      }
      
    • finally features

      • Statements controlled by finally will be executed unless the JVM exits
  • sample code

    public class FileOutputStreamDemo04 {
        public static void main(String[] args) {
            //Add finally to release resources
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream("myByteStream\\fos.txt");
                fos.write("hello".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    

2.6 Byte stream read data (read data one byte at a time)[Application]

  • byte input stream

    • FileInputStream(String name): Creates a FileInputStream by opening a connection to the actual file, named by the pathname name in the file system
  • Steps for reading data from a byte input stream

    • Create a byte input stream object
    • Call the read data method of the byte input stream object
    • release resources
  • sample code

    public class FileInputStreamDemo01 {
        public static void main(String[] args) throws IOException {
            //Create a byte input stream object
            //FileInputStream(String name)
            FileInputStream fis = new FileInputStream("myByteStream\\fos.txt");
    
            int by;
            /*
                fis.read(): read data
                by=fis.read(): Assign the read data to by
                by != -1: Determine whether the read data is -1
             */
            while ((by=fis.read())!=-1) {
                System.out.print((char)by);
            }
    
            //release resources
            fis.close();
        }
    }
    

2.7 Copy files by byte stream [Application]

  • case requirements

    ​ Copy "E:\itcast\window.txt" to "window.txt" in the module directory (the file can be any file)

  • Implementation steps

    • Copying a text file actually reads the content of the text file from one file (data source) and writes it to another file (destination)

    • data source:

      ​ E:\itcast\window.txt — read data — InputStream — FileInputStream

    • destination:

      ​ myByteStream\window.txt — write data — OutputStream — FileOutputStream

  • Code

    public class CopyTxtDemo {
        public static void main(String[] args) throws IOException {
            //Create a byte input stream object from a data source
            FileInputStream fis = new FileInputStream("E:\\itcast\\outside the window.txt");
            //Create a byte output stream object based on the destination
            FileOutputStream fos = new FileOutputStream("myByteStream\\outside the window.txt");
    
            //Read and write data, copy text files (read one byte at a time, write one byte at a time)
            int by;
            while ((by=fis.read())!=-1) {
                fos.write(by);
            }
    
            //release resources
            fos.close();
            fis.close();
        }
    }
    

2.8 byte stream read data (read one byte array data at a time) [Application]

  • Method for reading an array of bytes at a time

    • public int read(byte[] b): read up to b.length bytes of data from the input stream
    • Returns the total number of bytes read into the buffer, that is, the actual number of bytes read
  • sample code

    public class FileInputStreamDemo02 {
        public static void main(String[] args) throws IOException {
            //Create a byte input stream object
            FileInputStream fis = new FileInputStream("myByteStream\\fos.txt");
    
            byte[] bys = new byte[1024]; //1024 and its integer multiples
            int len;//The effective number of bytes read this time---z
          	//cyclic read
            while ((len=fis.read(bys))!=-1) {
                System.out.print(new String(bys,0,len));
            }
    
            //release resources
            fis.close();
        }
    }
    

2.9 Copy files by byte stream [Application]

  • case requirements

    ​ Copy "E:\itcast\mn.jpg" to "mn.jpg" in the module directory (the file can be any file)

  • Implementation steps

    • Create a byte input stream object from a data source
    • Create a byte output stream object based on the destination
    • Read and write data, copy pictures (read one byte array at a time, write one byte array at a time)
    • release resources
  • Code

    public class CopyJpgDemo {
        public static void main(String[] args) throws IOException {
            //Create a byte input stream object from a data source
            FileInputStream fis = new FileInputStream("E:\\itcast\\mn.jpg");
            //Create a byte output stream object based on the destination
            FileOutputStream fos = new FileOutputStream("myByteStream\\mn.jpg");
    
            //Read and write data, copy pictures (read one byte array at a time, write one byte array at a time)
            byte[] bys = new byte[1024];
            int len;
            while ((len=fis.read(bys))!=-1) {
                fos.write(bys,0,len);
            }
    
            //release resources
            fos.close();
            fis.close();
        }
    }
    

3. Byte buffer stream

3.1 Construction method of byte buffer stream [Application]

  • Introduction to Byte Buffer Streams

    • lBufferOutputStream: This class implements a buffered output stream. By setting such an output stream, an application can write bytes to the underlying output stream without causing the underlying system to call for each byte written
    • lBufferedInputStream: Creating a BufferedInputStream will create an array of internal buffers. As bytes are read or skipped from the stream, the internal buffer will be refilled as needed from the contained input stream, many bytes at a time
  • Construction method:

    method nameillustrate
    BufferedOutputStream(OutputStream out)Create a byte buffered output stream object
    BufferedInputStream(InputStream in)Create a byte buffered input stream object
  • sample code

    public class BufferStreamDemo {
        public static void main(String[] args) throws IOException {
            //Byte buffered output stream: BufferedOutputStream(OutputStream out)
     
            BufferedOutputStream bos = new BufferedOutputStream(new 				                                       FileOutputStream("myByteStream\\bos.txt"));
            //write data
            bos.write("hello\r\n".getBytes());
            bos.write("world\r\n".getBytes());
            //release resources
            bos.close();
        
    
            //Byte buffered input stream: BufferedInputStream(InputStream in)
            BufferedInputStream bis = new BufferedInputStream(new                                                          FileInputStream("myByteStream\\bos.txt"));
    
            //Read data one byte at a time
    //        int by;
    //        while ((by=bis.read())!=-1) {
    //            System.out.print((char)by);
    //        }
    
            //Read byte array data one at a time
            byte[] bys = new byte[1024];
            int len;
            while ((len=bis.read(bys))!=-1) {
                System.out.print(new String(bys,0,len));
            }
    
            //release resources
            bis.close();
        }
    }
    

3.2 byte buffer stream copy video [application]

  • case requirements

    Copy "E:\itcast\Byte Stream Copy Picture.avi" to "Byte Stream Copy Picture.avi" in the module directory

  • Implementation steps

    • Create a byte input stream object from a data source
    • Create a byte output stream object based on the destination
    • Read and write data, copy video
    • release resources
  • Code

    public class CopyAviDemo {
        public static void main(String[] args) throws IOException {
    
            //copy video
    //        method1();
          	 method2();
    
        }
    
        //Byte buffer stream reads and writes one byte array at a time
        public static void method2() throws IOException {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\itcast\\byte stream copy image.avi"));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myByteStream\\byte stream copy image.avi"));
    
            byte[] bys = new byte[1024];
            int len;
            while ((len=bis.read(bys))!=-1) {
                bos.write(bys,0,len);
            }
    
            bos.close();
            bis.close();
        }
    
        //Byte-buffered streams read and write one byte at a time
        public static void method1() throws IOException {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\itcast\\byte stream copy image.avi"));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myByteStream\\byte stream copy image.avi"));
    
            int by;
            while ((by=bis.read())!=-1) {
                bos.write(by);
            }
    
            bos.close();
            bis.close();
        }
    
    }
    

Tags: Java

Posted by fredted40x on Thu, 09 Feb 2023 06:41:50 +0530