JAVA advanced IO stream

IO

Use of File class

Get function of File class

public String getAbsolutePath(): get absolute path
public String getPath(): get path
public String getName(): get the name
public String getParent(): get the directory path of the upper level file. If none, null is returned
public long length(): get the length of the file (i.e. the number of bytes). Cannot get the length of the directory.
public long lastModified(): gets the last modification time, in milliseconds
public String[] list(): get the name array of all files or file directories in the specified directory
public File[] listFiles(): get the File array of all files or File directories in the specified directory

Rename function of File class

public boolean renameTo(File dest): rename the file to the specified file path

Judgment function of File class

public boolean isDirectory(): judge whether it is a file directory
public boolean isFile(): judge whether it is a file
public boolean exists(): judge whether it exists
public boolean canRead(): judge whether it is readable
public boolean canWrite(): judge whether it is writable
public boolean isHidden(): judge whether to hide

Creation function of File class

public boolean createNewFile(): creates a file. If the file exists, it will not be created and false will be returned
public boolean mkdir(): create a file directory. If this file directory exists, it will not be created. If the upper directory of this file directory does not exist, it will not be created.
public boolean mkdirs(): create a file directory. If the upper file directory does not exist, create it together

Delete function of File class

public boolean delete(): deletes files or folders

Java IO principle

input: read external data (data from disk, optical disc and other storage devices) into the program (memory).
Output: output program (memory) data to disk, optical disc and other storage devices.

Classification of flow

According to different operation data units, it is divided into byte stream (8 bit) and character stream (16 bit)
According to the flow direction of data flow, it is divided into input flow and output flow
According to the different roles of flow, it can be divided into node flow and processing flow


FileReader

    @Test
    public void testFileReader(){
        FileReader fr = null;
        try {
            //1. Instantiate the object of File class to indicate the File to be operated
            File file = new File("hello.txt");//Compared to the current Module
            //2. Provide specific flow
            fr = new FileReader(file);

            //3. Data reading
            //Read returns a character of read(). If the end of the file is reached, - 1 is returned
            //Mode 1:
//        int data = fr.read();
//        while(data != -1){
//            System.out.print((char)data);
//            data = fr.read();
//        }

            //Mode 2: grammatical modification of mode 1
            int data;
            while((data = fr.read()) != -1){
                System.out.print((char)data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. Close the flow
//            try {
//                if(fr != null)
//                    fr.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
            //or
            if(fr != null){
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

Upgrade the read() operation: use the overloaded method of read

 @Test
    public void testFileReader1()  {
        FileReader fr = null;
        try {
            //1. Instantiation of file class
            File file = new File("hello.txt");

            //2. Instantiation of FileReader stream
            fr = new FileReader(file);

            //3. Read in operation
            //read(char[] cbuf): returns the number of characters read into the cbuf array each time. If the end of the file is reached, - 1 is returned
            char[] cbuf = new char[5];
            int len;
            while((len = fr.read(cbuf)) != -1){
                //Mode 1:
                //Wrong writing
//                for(int i = 0;i < cbuf.length;i++){
//                    System.out.print(cbuf[i]);
//                }
                //Correct writing
//                for(int i = 0;i < len;i++){
//                    System.out.print(cbuf[i]);
//                }
                //Mode 2:
                //The wrong way of writing corresponds to the wrong way of writing in mode 1
//                String str = new String(cbuf);
//                System.out.print(str);
                //Correct writing
                String str = new String(cbuf,0,len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fr != null){
                //4. Closure of resources
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

    }

FileWriter

   @Test
    public void testFileWriter() {
        FileWriter fw = null;
        try {
            //1. Provide the object of File class to indicate the File to be written out
            File file = new File("hello.txt");
            //2. Provide the object of FileWriter for writing out data
            fw = new FileWriter(file,false);
            //3. Write out the operation
            fw.write("I love java!\n");
            fw.write("you need to love java!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. Closing of flow resources
            if(fw != null){

                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

FileReader and FileWriter implement replication

  @Test
    public void testFileReaderFileWriter() {
        FileReader fr = null;
        FileWriter fw = null;
        try {
            //1. The File created and the class read in are indicated
            File srcFile = new File("hello.txt");
            File destFile = new File("hello2.txt");

            //Character streams cannot be used to process byte data such as pictures
//            File srcFile = new File("1.jpg");
//            File destFile = new File("2.jpg");
            //2. Create objects for input and output streams
            fr = new FileReader(srcFile);
            fw = new FileWriter(destFile);
            //3. Data reading and writing
            char[] cbuf = new char[5];
            int len;//Record the number of characters read into the cbuf array each time
            while((len = fr.read(cbuf)) != -1){
                //Write len characters at a time
                fw.write(cbuf,0,len);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fw != null)
                    fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if(fr != null)
                    fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

FileInputStream and OutputStream are the same

/*
    Copy the picture
     */
    @Test
    public void testFileInputOutputStream()  {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            //
            File srcFile = new File("1.jpg");
            File destFile = new File("2.jpg");

            //
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);

            //Replication process
            byte[] buffer = new byte[5];
            int len;
            while((len = fis.read(buffer)) != -1){
                fos.write(buffer,0,len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fos != null){
                //
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

    }

Copy of files under the specified path

   //Copy of files under the specified path
    public void copyFile(String srcPath,String destPath){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            //
            File srcFile = new File(srcPath);
            File destFile = new File(destPath);

            //
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);

            //Replication process
            byte[] buffer = new byte[1024];
            int len;
            while((len = fis.read(buffer)) != -1){
                fos.write(buffer,0,len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fos != null){
                //
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        
    }

One of the processing streams is BufferedInputStream and BufferedOutputStream

  //Method for realizing file copying
    public void copyFileWithBuffered(String srcPath,String destPath){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            //1. Documentation
            File srcFile = new File(srcPath);
            File destFile = new File(destPath);
            //2. Flow generation
            //2.1 node flow
            FileInputStream fis = new FileInputStream((srcFile));
            FileOutputStream fos = new FileOutputStream(destFile);
            //2.2 buffer flow
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            //3. Copy details: read, write
            byte[] buffer = new byte[1024];
            int len;
            while((len = bis.read(buffer)) != -1){
                bos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. Resource shutdown
            //Requirements: first close the flow of the outer layer, and then close the flow of the inner layer
            if(bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if(bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            //Note: when closing the outer layer flow, the inner layer flow will also be closed automatically. The closure of inner laminar flow can be omitted
//        fos.close();
//        fis.close();
        }
    }

One of the processing streams is BufferedReader and BufferedWriter

    /*
    Use BufferedReader and BufferedWriter to copy text files

     */
    @Test
    public void testBufferedReaderBufferedWriter(){
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            //Create files and corresponding streams
            br = new BufferedReader(new FileReader(new File("a.txt")));
            bw = new BufferedWriter(new FileWriter(new File("a1.txt")));

            //Read / write operation
            //Method 1: use char [] array
//            char[] cbuf = new char[1024];
//            int len;
//            while((len = br.read(cbuf)) != -1){
//                bw.write(cbuf,0,len);
//    //            bw.flush();
//            }

            //Method 2: use String
            String data;
            while((data = br.readLine()) != null){
                //Method 1:
//                bw.write(data + "\n");//data does not contain line breaks
                //Method 2:
                bw.write(data);//data does not contain line breaks
                bw.newLine();//Provides line feed operations

            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //close resource
            if(bw != null){

                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

    }

Process stream 2: Transform streams InputStreamReader and OutputStreamWriter

/*
Use InputStreamReader and OutputStreamWriter together
 */
@Test
public void test2() throws Exception {
    //1. Document making and flow making
    File file1 = new File("a.txt");
    File file2 = new File("b.txt");

    FileInputStream fis = new FileInputStream(file1);
    FileOutputStream fos = new FileOutputStream(file2);

    InputStreamReader isr = new InputStreamReader(fis,"utf-8");
    OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk");

    //2. Reading and writing process
    char[] cbuf = new char[20];
    int len;
    while((len = isr.read(cbuf)) != -1){
        osw.write(cbuf,0,len);
    }
    //3. Close resources
    isr.close();
    osw.close();
}

Processing stream 3 standard input and output streams (understand)

System.in: standard input stream, which is input from the keyboard by default
System.out: standard output stream, which is output from the console by default. The setIn(InputStream is) / setOut(PrintStream ps) mode of system class re specifies the input and output streams.

Processing stream 4: print stream (understand)

PrintStream and PrintWriter

Processing flow 5: data flow (understanding)

DataInputStream and DataOutputStream

Processing flow 6: object flow

ObjectInputStream and ojbectoutputstream

summary

① Streams are used to process data.
② When processing data, you must first clarify the data source and data destination
1) The data source can be a file or a keyboard.
2) The data destination can be a file, display or other device.
③ The stream only helps data transmission and processes the transmitted data, such as filtering, conversion, etc.

Keywords: Java linked list

Added by Pyro on Tue, 08 Mar 2022 05:40:15 +0200