File & Recursive & Byte Stream

Posted by nimbus on Thu, 15 Aug 2019 13:21:02 +0200

1.File class

1.1 File Class Overview and Construction Method [Application]

  • Introduction to File Class

    • It is an abstract representation of file and directory pathnames
    • Files and directories can be encapsulated as objects through File
    • For File, the encapsulation is not a real file, just a path name. It may or may not exist. The future is to convert the content of this path into concrete existence through specific operations.
  • Construction Method of File Class

    Method name Explain
    File(String pathname) Create a new File instance by converting a given path name string to an abstract path name
    File(String parent, String child) Create a new File instance from the parent path name string and the child path name string
    File(File parent, String child) Create a new File instance from the parent Abstract path name and child path name string
  • Sample code

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

1.2 File Class Creation Function [Application]

  • Method Classification

    Method name Explain
    public boolean createNewFile() When a file with that name does not exist, create a new empty file named by the abstract path name
    public boolean mkdir() Create a directory named by this abstract path name
    public boolean mkdirs() Create directories named by this abstract path name, including any necessary but non-existent 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'm going to create a directory JavaSE in the E:\ itcase 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.3 File Class Judgment and Acquisition Function [Application]

  • Judgment function

    Method name Explain
    public boolean isDirectory() Test whether the File represented by this abstract path name is a directory
    public boolean isFile() Test whether the File represented by this abstract path name is a file
    public boolean exists() Test whether the File represented by this abstract path name exists
  • Acquisition function

    Method name Explain
    public String getAbsolutePath() Returns the absolute path name string for this abstract path name
    public String getPath() Convert this abstract path name to a path name string
    public String getName() Returns the name of the file or directory represented by this abstract path name
    public String[] list() Returns the name string array of files and directories in the directory represented by this abstract path name
    public File[] listFiles() Returns an array of File objects for files and directories in the directory represented by this abstract path name
  • Sample code

    public class FileDemo04 {
        public static void main(String[] args) {
            //Create a File object
            File f = new File("myFile\\java.txt");
    
    //        Public Boolean is Directory (): Test whether the File represented by this abstract path name is a directory
    //        public boolean isFile(): Test whether the File represented by this abstract path name is a file
    //        public boolean exists(): Test whether the File represented by this abstract path name exists
            System.out.println(f.isDirectory());
            System.out.println(f.isFile());
            System.out.println(f.exists());
    
    //        public String getAbsolutePath(): Returns the absolute path name string for this abstract path name
    //        public String getPath(): Converts this abstract path name to a path name string
    //        public String getName(): Returns the name of the file or directory represented by this abstract path name
            System.out.println(f.getAbsolutePath());
            System.out.println(f.getPath());
            System.out.println(f.getName());
            System.out.println("--------");
    
    //        public String[] list(): Returns the name string array of files and directories in the directory represented by this abstract path name
    //        public File[] listFiles(): Returns an array of File objects for files and directories in the directory represented by this abstract path name
            File f2 = new File("E:\\itcast");
    
            String[] strArray = f2.list();
            for(String str : strArray) {
                System.out.println(str);
            }
            System.out.println("--------");
    
            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.4 File class deletion function [application]

  • Method Classification

    Method name Explain
    public boolean delete() Delete files or directories represented by this abstract path name
  • 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 the 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 under that 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());
        }
    }
    
  • The Difference between Absolute Path and Relative Path

    • Absolute path: A complete path name that locates the file it represents without any additional information. For example: E: itcast java. TXT
    • Relative paths: Information from other pathnames must be used for interpretation. For example: myFilejava.txt

2. Recursion

2.1 Recursion [Application]

  • Introduction to Recursion

    • From a programming point of view, recursion refers to the phenomenon of calling the method itself in the method definition.
    • Converting a complex problem layer by layer into a smaller problem similar to the original problem to solve
    • Recursive strategy requires only a small number of programs to describe the multiple repeated computations required in the process of problem solving.
  • Basic use of recursion

    public class DiGuiDemo {
        public static void main(String[] args) {
            //Looking back on the problem of the immortal rabbit and finding the logarithm of the rabbit in the 20th month
            //Number of rabbits per month: 1, 1, 2, 3, 5, 8,...
            int[] arr = new int[20];
    
            arr[0] = 1;
            arr[1] = 1;
    
            for (int i = 2; i < arr.length; i++) {
                arr[i] = arr[i - 1] + arr[i - 2];
            }
            System.out.println(arr[19]);
            System.out.println(f(20));
        }
    
        /*
            The first step in Solving Recursive problems is to define a method:
                Define a method f(n): Represents the rabbit logarithm of the nth month
                So, how to express the rabbit logarithm in the n-1 month? f(n-1)
                Similarly, how should the N-2 month rabbit logarithm be represented? f(n-2)
    
            StackOverflowError:Throwing an application too recursive when a stack overflow occurs
         */
        public static int f(int n) {
            if(n==1 || n==2) {
                return 1;
            } else {
                return f(n - 1) + f(n - 2);
            }
        }
    }
    
  • Recursive considerations

    • There must be an exit for recursion. Otherwise, memory overflow
    • Although recursion has exits, the number of recursions should not be too many. Otherwise, memory overflow

2.2 Recursive factorial [application]

  • Case requirements

    The factorial of 5 is calculated recursively and the result is output in the console.

  • code implementation

    public class DiGuiDemo01 {
        public static void main(String[] args) {
            //Call method
            int result = jc(5);
            //Output results
            System.out.println("5 The factorial is:" + result);
        }
    
        //Define a method for recursive factorization with parameters of an int type variable
        public static int jc(int n) {
            //Determine whether the value of the variable is 1 within the method
            if(n == 1) {
                //Yes: Return 1
                return 1;
            } else {
                //No: Return n*(n-1)!
                return n*jc(n-1);
            }
        }
    }
    

2.3 Recursive traversal directory [application]

  • Case requirements

    Given a path (E: itcast), iterate through all the contents of the directory by recursion, and output the absolute path of all files to the console.

  • code implementation

    public class DiGuiDemo02 {
        public static void main(String[] args) {
            //Create a File object based on a given path
    //        File srcFile = new File("E:\\itcast");
            File srcFile = new File("E:\\itheima");
    
            //Call method
            getAllFilePath(srcFile);
        }
    
        //Define a method to get everything in a given directory with the File object created in step 1 as a parameter
        public static void getAllFilePath(File srcFile) {
            //Gets a File array of all files or directories in a given File directory
            File[] fileArray = srcFile.listFiles();
            //Traverse the File array to get each File object
            if(fileArray != null) {
                for(File file : fileArray) {
                    //Determine whether the File object is a directory
                    if(file.isDirectory()) {
                        //Yes: Recursive calls
                        getAllFilePath(file);
                    } else {
                        //No: Get absolute path output in the console
                        System.out.println(file.getAbsolutePath());
                    }
                }
            }
        }
    }
    

3.IO Flow

3.1 Overview and Classification of IO Flows [Understanding]

  • IO Flow Introduction
    • IO: Input/Output
    • Stream: It is an abstract concept and a general term for data transmission. That is to say, the transmission of data between devices is called stream, and the essence of stream is data transmission.
    • IO stream is used to deal with data transmission between devices. Common applications: file copy; file upload; file download
  • Classification of IO Flows
    • 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
  • Use scenarios for IO streams
    • If you are working on plain text files, preferring character streams
    • If the operation is a picture, video, audio and other binary files. Preferred byte streams
    • If the file type is uncertain, byte streams are preferred. Byte streams are omnipotent streams

3.2 byte streaming data [application]

  • Byte stream abstract base class

    • InputStream: This abstract class is a superclass of all classes representing byte input streams
    • OutputStream: This abstract class is a superclass of all classes representing byte output streams
    • Subclass Name Characteristics: Subclass names are suffixes with their parent names as subclass names
  • Byte Output Stream

    • FileOutputStream(String name): Creates a file output stream to write to a file with the specified name
  • Steps for streaming data using byte output

    • Create byte output stream objects (call system functions to create files, create byte output stream objects, let byte output stream objects point to files)
    • Write Data Method for Calling Byte Output Stream Objects
    • Release resources (close the file output stream and release any system resources associated with the stream)
  • Sample code

    public class FileOutputStreamDemo01 {
        public static void main(String[] args) throws IOException {
            //Create byte output stream objects
            //FileOutputStream(String name): Creates a file output stream to write to a file with the specified name
            FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt");
            /*
                Three things have been done:
                    A:Call system functions to create files
                    B:Create byte output stream object
                    C:Let byte output stream object point to the created file
             */
    
            //void write(int b): Writes the specified byte to the file output stream
            fos.write(97);
    //        fos.write(57);
    //        fos.write(55);
    
            //Finally, we need to release resources.
            //void close(): Close the file output stream and release any system resources associated with the stream.
            fos.close();
        }
    }
    

Three Ways of 3.3 Byte Streaming Data [Application]

  • Method Classification of Writing Data

    Method name Explain
    void write(int b) Write the specified byte to the file output stream one byte at a time
    void write(byte[] b) Write b.length bytes from a specified byte array to the output stream of this file to write one byte array data at a time
    void write(byte[] b, int off, int len) Write len bytes from the specified byte array and offset off to the file output stream to write part of the data of one byte array at a time.
  • Sample code

    public class FileOutputStreamDemo02 {
        public static void main(String[] args) throws IOException {
            //FileOutputStream(String name): Creates a file output stream to write to a file with the specified name
            FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt");
            //new File(name)
    //        FileOutputStream fos = new FileOutputStream(new File("myByteStream\\fos.txt"));
    
            //FileOutputStream(File file): Creates a file output stream to write to a file represented by a specified File object
    //        File file = new File("myByteStream\\fos.txt");
    //        FileOutputStream fos2 = new FileOutputStream(file);
    //        FileOutputStream fos2 = new FileOutputStream(new File("myByteStream\\fos.txt"));
    
            //void write(int b): Writes the specified byte to the 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 a specified byte array to the file output stream
    //        byte[] bys = {97, 98, 99, 100, 101};
            //byte[] getBytes(): Returns an array of bytes corresponding to a string
            byte[] bys = "abcde".getBytes();
    //        fos.write(bys);
    
            //void write(byte[] b, int off, int len): Writes len bytes from the specified byte array and offset off to the file output stream
    //        fos.write(bys,0,bys.length);
            fos.write(bys,1,3);
    
            //Releasing resources
            fos.close();
        }
    }
    

Two Small Problems of 3.4 Byte Streaming Data [Application]

  • How to Realize Line Breaking in Byte Stream Writing Data

    • windows:\r\n
    • linux:\n
    • mac:\r
  • How to Realize Additional Writing of Byte Stream Writing Data

    • public FileOutputStream(String name,boolean append)
    • Create a file output stream to write to the file with the specified name. If the second parameter is true, 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 byte output stream objects
    //        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());
            }
    
            //Releasing resources
            fos.close();
        }
    }
    

3.5 byte streaming data plus exception handling [application]

  • Exception handling format

    • try-catch-finally

      try{
      	Code that may have exceptions;
      } catch (variable name of exception class name){
      	Exception handling code;
      }finally{
      	Perform all cleaning operations;
      }
      
    • finally characteristics

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

    public class FileOutputStreamDemo04 {
        public static void main(String[] args) {
            //Join 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();
                    }
                }
            }
        }
    }
    

3.6 byte stream read data (read one byte at a time) [application]

  • Byte input stream

    • FileInputStream(String name): Create a FileInputStream by opening a connection to the actual file named by the path name in the file system
  • Step of reading data from byte input stream

    • Create byte input stream objects
    • Method of calling byte input stream object to read data
    • Releasing resources
  • Sample code

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

3.7 Byte Stream Copy Text File [Application]

  • Case requirements

    Copy "E: itcast inside and outside windows. txt" to "inside and outside windows. txt" in the module directory

  • 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 sources:

      E:itcastinside and outside windows.txt-read data-InputStream-FileInputStream

    • Destination:

      myByteStream Windows in and out. txt - Write data - OutputStream - FileOutputStream

  • code implementation

    public class CopyTxtDemo {
        public static void main(String[] args) throws IOException {
            //Creating byte input stream objects from data sources
            FileInputStream fis = new FileInputStream("E:\\itcast\\Inside and outside the window.txt");
            //Create byte output stream objects based on destination
            FileOutputStream fos = new FileOutputStream("myByteStream\\Inside and 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);
            }
    
            //Releasing resources
            fos.close();
            fis.close();
        }
    }
    

3.8 byte stream read data (read one byte array data at a time) [application]

  • A Method of 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 byte input stream objects
            FileInputStream fis = new FileInputStream("myByteStream\\fos.txt");
    
            /*
                hello\r\n
                world\r\n
    
                First time: hello
                Second:  r nwor
                Third: ldrnr
    
             */
    
            byte[] bys = new byte[1024]; //1024 and its integer multiple
            int len;
            while ((len=fis.read(bys))!=-1) {
                System.out.print(new String(bys,0,len));
            }
    
            //Releasing resources
            fis.close();
        }
    }
    

3.9 Byte Stream Copy Pictures [Application]

  • Case requirements

    Copy "E:itcastmn.jpg" to "mn.jpg" in the module directory

  • Implementation steps

    • Creating byte input stream objects from data sources
    • Create byte output stream objects based on destination
    • Read and write data, copy pictures (read an array of bytes at a time, write an array of bytes at a time)
    • Releasing resources
  • code implementation

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

Topics: Java Windows Programming Linux