Java note IO stream

Posted by hnxuying on Thu, 17 Feb 2022 16:08:03 +0100

1, Use of File class

1. Use of file class

  • Use of File class
  • ① An object of the File class that represents a File or a File directory (commonly known as a folder)
  • ② The File class is declared in Java Under IO package
    ③ The File class involves the creation, deletion, renaming, modification time, File size and other methods of files or File directories, and does not involve the operation of writing or reading File contents. If you need to read or write the contents of the File, you must use the IO stream to complete it.
  • ④ Objects of subsequent File classes are often passed as parameters to the stream constructor, indicating the "end point" of reading or writing

Specific usage:

 * 1.How to create file Instance of class
 * ①File(String filePath):with filePath Create for path File Object, which can be an absolute path or a relative path
 * ②File(String parentPath,String childPath):with parentPath As the parent path, childPath Create for subpath File Object.
 * ③File(File parentFile,String childPath):According to a parent File Object and sub file path creation File object
 * 2.
 *   Relative path: the specified path compared to a certain path.
 *   Absolute path: the path to the file or file directory including the drive letter
 *
 * 3.path separator 
 *      windows:\\
 *      unix:/
 * 4.Java The program supports cross platform operation, so the path separator should be used with caution.
 *
 * 5.In order to solve this hidden danger, File A constant class is provided:
 *   public  static final String separator. 
 *   Provide separators dynamically according to the operating system.
 *
 * File file1= new File("d:\\Work\\info.txt");
 * File file2= new File("d:"+ File.separator+ "Work"+ File.separator+ "info.txt");
 * File file3= new File("d:/Work");

2. Common methods in 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
  • The following two methods apply to file directories:
  • 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

2, IO stream principle and stream classification

1. Principle of IO flow

  • I/O is the abbreviation of Input/Output. I/O technology is a very practical technology for processing data transmission between devices. Such as reading / writing files, network communication, etc.
  • In Java program, the input / output operation of data is carried out in the way of "stream".
    java. Various "stream" classes and interfaces are provided under the IO package to obtain different kinds of data and input or output data through standard methods.
  • 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.

2. Classification of flow

3, File stream

1. Steps for FileReader to read data:

① Create a stream object and load an existing file into the stream.
FileReaderfr= new FileReader(new File("Test.txt"));

② Create an array to store data temporarily
char[] ch= new char[1024];
③ Call the read method of the stream object to read the data in the stream into the array.
fr.read(ch);
④ Close resource
fr.close();

2. Steps for filewriter to write data:

① Create a stream object and load an existing file into the stream.
FileWriter fw= new FileWriter(new File("Test.txt"));

② Call the read method of the stream object to read the data in the stream into the array.
fw.writer("adawdawfad");
③ Close resource
fw.close();

3. Use FileReader and FileWriter to copy text files

import org.junit.Test;
import java.io.*;

public class FileReaderWriterTest {

    @Test
    public void test4() {
        FileReader fr = null;
        FileWriter fw = null;
        try {
            //1. Create an object of File class to indicate the files read in and written out
            File srcFile = new File("hello1.txt");
            File srcFile2 = new File("hello2..txt");

            //Character streams cannot be used to process byte data such as pictures
//            File srcFile = new File("love and friendship. jpg");
//            File srcFile2 = new File("love and friendship 1.jpg");

            //2. Create objects for input and output streams
            fr = new FileReader(srcFile);
            fw = new FileWriter(srcFile2);

            //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 {
            //4. Close stream resources
            //Mode 1:
//            try {
//                if(fw != null)
//                    fw.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }finally{
//                try {
//                    if(fr != null)
//                        fr.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
            //Mode 2:
            try {
                if(fw != null)
                    fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

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

4. Test the method of copying files using FileInputStream and FileOutputStream

import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileIOPutTest {

    //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();
                }

            }
        }
    }

    @Test
    public void testCopyFile(){

        long start = System.currentTimeMillis();

//        String srcPath = "C:\\Users\\29433\\Desktop\\164.jpg";
//        String destPath = "C:\\Users\\29433\\Desktop\\164.jpg";

        String srcPath = "hello.txt";
        String destPath = "hello3.txt";

        copyFile(srcPath,destPath);

        long end = System.currentTimeMillis();

        System.out.println("The time taken for the copy operation is:" + (end - start));//1
    }
}

4, Buffer stream

  • In order to improve the speed of data reading and writing, the Java API provides stream classes with buffer function. When using these stream classes, an internal buffer array will be created, and a buffer of 8192 bytes (8Kb) will be used by default.

  • The buffer flow should be "nested" on the corresponding node flow. According to the data operation unit, the buffer flow can be divided into:

    • BufferedInputStream and BufferedOutputStream
    • BufferedReader and BufferedWriter
  • When reading data, the data is read into the buffer by block, and subsequent read operations directly access the buffer

  • When using BufferedInputStream to read byte files, BufferedInputStream will read 8192 bytes (8Kb) from the file at one time and store them in the buffer until the buffer is full, and then read the next 8192 byte array from the file again.

  • When writing bytes to the stream, they will not be directly written to the file. They will be written to the buffer first. BufferedOutputStream will not write the data in the buffer to the file at one time until the buffer is full. Use the method flush() to force all the contents of the buffer to be written to the output stream

  • The order in which the flow is closed is opposite to the order in which it is opened. As long as you close the outermost flow, closing the outermost flow will also close the inner node flow accordingly

  • Use of the flush() method: manually write the contents of the buffer to the file

  • If it is the close() method of the stream object with buffer, it will not only close the stream, but also refresh the buffer before closing the stream. After closing, it can't be written out again.

1. Buffer stream (byte type) realizes the copy of non text files

import org.junit.Test;

import java.io.*;

/**
 * One of the processing streams: the use of buffer streams
 *
 *  1.Buffer stream:
 *  BufferedInputStream
 *  BufferedOutputStream
 *  BufferedReader
 *  BufferedWriter
 */
public class BufferedTest {

    /**
     * Copy non text files
     */
    @Test
    public void BufferedStreamTest(){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            //1. Documentation
            File srcFile = new File("Love and friendship.jpg");
            File destFile = new File("Love and friendship 3.jpg");
            //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[10];
            int len;
            while((len = bis.read(buffer)) != -1){
                bos.write(buffer,0,len);
//                bos.flush();// refresh buffer 
            }
        } 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();
        }
    }
}

2. The buffer stream (character type) realizes the copy of text files

import org.junit.Test;
import java.io.*;

public class BufferedTest {
  /**
     * Use BufferedReader and BufferedWriter to copy text files
     */
    @Test
    public void test4(){
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            //Create files and corresponding streams
            br = new BufferedReader(new FileReader(new File("dbcp.txt")));
            bw = new BufferedWriter(new FileWriter(new File("dbcp1.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();
                }
            }
        }
    }
}

5, Conversion flow

1. The concept of conversion stream and the use of InputStreamReader

  • Conversion stream provides conversion between byte stream and character stream
  • The Java API provides two transformation streams:
    • InputStreamReader: convert InputStream to Reader
      • The input stream of bytes is converted into the input stream of characters according to the specified character set.
      • Need to "socket" with InputStream.
      • constructor
        • public InputStreamReader(InputStreamin)
        • public InputSreamReader(InputStreamin,StringcharsetName)
        • For example: Reader isr= new InputStreamReader(System.in, "gbk");
    • OutputStreamWriter: converts the Writer to OutputStream
      • Realize the conversion of the output stream of characters into the output stream of bytes according to the specified character set.
      • Need to "socket" with OutputStream.
      • constructor
        • public OutputStreamWriter(OutputStreamout)
        • public OutputSreamWriter(OutputStreamout,StringcharsetName)
  • When the data in the byte stream is all characters, the operation of converting to character stream is more efficient.
  • Many times, we use transform stream to deal with the problem of file scrambling. Realize the function of encoding and decoding.

2. The conversion stream realizes the reading and writing of files

import org.junit.Test;

import java.io.*;

/**
 * Processing flow 2: use of conversion flow
 * 1.Conversion stream: belongs to character stream
 *      InputStreamReader: Converts a byte input stream to a character input stream
 *      OutputStreamWriter: Converts the output stream of one character to the output stream of bytes
 *
 * 2.Function: provide conversion between byte stream and character stream
 *
 * 3.Decoding: byte, byte array -- > character array, string
 *   Encoding: character array, string -- > byte, byte array
 *
 * 4.character set
 */
public class InputStreamReaderTest {
    /**
     * Try catch finally should still be used to handle exceptions at this time
     * Use InputStreamReader and OutputStreamWriter together
     */
    @Test
    public void test2() throws IOException {
        //1. Document making and flow making
        File file1 = new File("dbcp.txt");
        File file2 = new File("dbcp_gbk.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();
    }
}

Topics: Java Back-end OOP