Java - IO stream (node stream or file stream)

Posted by genius_supreme on Sun, 12 Sep 2021 21:35:43 +0200

IO stream (node stream or file stream)

Prerequisite knowledge
First, let's understand the system of the main two streams, and then look at the use of the four basic streams.
Flow architecture

InputStream & Reader

  • InputStream and Reader are the base classes for all input streams.
  • InputStream (typical implementation: FileInputStream)
    • int read()
    • int read(byte[] b)
    • int read(byte[] b, int off, int len)
  • Reader (typical implementation: FileReader)
    • int read()
    • int read(char [] c)
    • int read(char [] c, int off, int len)
  • The file IO resource opened in the program does not belong to the resource in memory, and the garbage collection mechanism cannot recycle the resource, so the file IO resource should be explicitly closed.
  • FileInputStream gets input bytes from a file in the file system. FileInputStream is used to read raw byte streams such as non text data. To read the character stream, you need to use FileReader.

InputStream

  • int read()
    Reads the next byte of data from the input stream. Returns an int byte value in the range 0 to 255. If no bytes are available because the end of the stream has been reached, the value - 1 is returned.
  • int read(byte[] b)
    Read up to b.length bytes of data into a byte array from this input stream. If no bytes are available because the end of the stream has been reached, the value - 1 is returned. Otherwise, the number of bytes actually read is returned as an integer.
  • int read(byte[] b, int off,int len) (not commonly used)
    Read the maximum len data bytes in the input stream into the byte array. An attempt was made to read len bytes, but the bytes read may also be less than this value. Returns the number of bytes actually read as an integer. If no bytes are available because the stream is at the end of the file, the value - 1 is returned.
  • public void close() throws IOException
    Close this input stream and release all system resources associated with the stream.

Reader

  • int read()
    Read a single character. Characters read as integers, ranging from 0 to 65535 (0x00-0xffff) (2-byte Unicode code). If the end of the stream has been reached, it returns - 1. (so if we want to read characters, we need to strong turn (char)).

  • int read(char[] cbuf)
    Reads characters into an array. Returns - 1 if the end of the stream has been reached. Otherwise, it returns the number of characters read this time.

  • int read(char[] cbuf,int off,int len) (not commonly used)
    Reads characters into a part of an array. Store in the array cbuf, start from off, and read len characters at most. Returns - 1 if the end of the stream has been reached. Otherwise, it returns the number of characters read this time.

  • public void close() throws IOException
    Close this input stream and release all system resources associated with the stream.
    explain:

    1. Exception handling: to ensure that flow resources can be closed. Try catch finally processing is required
    2. The read file must exist, otherwise FileNotFoundException will be reported.

OutputStream & Writer

  • OutputStream and Writer are also very similar:
    • void write(int b/int c);
    • void write(byte[] b/char[] cbuf);
    • void write(byte[] b/char[] buff, int off, int len);
    • void flush(); (some of the processing streams call refresh automatically, while others need to be called manually)
    • void close(); You need to refresh before closing this stream
    • Because the character stream directly takes the character as the operation unit, the Writer can replace the character array with a String, that is, take the String object as the parameter.
    • void write(String str);
    • void write(String str, int off, int len);
  • FileOutputStream obtains output bytes from a file in the file system. FileOutputStream is used to write out raw byte streams such as non text data. To write out the character stream, you need to use FileWriter.

OutputStream

  • void write(int b)
    Writes the specified byte to this output stream. The general convention of write is to write a byte to the output stream. The bytes to be written are the eight low bits of parameter b. The 24 high bits of b will be ignored. That is, write in the range of 0 ~ 255.
  • void write(byte[] b)
    Writes b.length bytes from the specified byte array to this output stream. The general convention of write(b) is that it should have exactly the same effect as calling write(b, 0, b.length).
  • void write(byte[] b,int off,int len)
    Writes len bytes from the offset off in the specified byte array to this output stream.
  • public void flush()throws IOException
    Refresh this output stream and force all buffered output bytes to be written out, calling this method indicates that these bytes should be written to their expected destination immediately.
  • public void close() throws IOException
    Close this output stream and release all system resources associated with the stream.

explain:

  • When writing a file, if the constructor FileOutputStream(file) is used, there is a file with the same name in the directory
    Pieces will be overwritten.
  • If the constructor FileOutputStream(file,true) is used, the file with the same name in the directory will not be overwritten, and the content will be appended at the end of the file content.

Writer

  • void write(int c)
    Write a single character. The character to be written is contained in the 16 low bits of the given integer value, and the 16 high bits are ignored. That is, write the Unicode code between 0 and 65535.
  • void write(char[] cbuf)
    Write character array.
  • void write(char[] cbuf,int off,int len)
    Writes a part of a character array. Starting from off, write len characters
  • void write(String str)
    Write string.
  • void write(String str,int off,int len)
    Writes a part of a string.
  • void flush()
    Flush the buffer of the stream, then write them to the expected destination immediately.
  • public void close() throws IOException
    Close this output stream and release all system resources associated with the stream.
    explain:
    1. For output operation, the corresponding File may not exist. No exception will be reported
    • If the File in the hard disk corresponding to File does not exist, this File will be automatically created during output.
    • If the File in the hard disk corresponding to File exists:
      • If the constructor used by the stream is: FileWriter(file,false) / FileWriter(file): overwrite the original file.
      • If the constructor used by the stream is: FileWriter(file,true): the original file will not be overwritten, but content will be added to the original file.

Node stream (or file stream)

Just understand the above roughly. Next, we will use them to input and output node stream data.
Input (reader character stream):

    @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 read in. 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);  // Forced transformation
//            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();
                }

            }
        }

    }
 

Output (writer character stream):

    @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("hello1.txt");

            //2. Provide FileWriter object for data writing
            fw = new FileWriter(file,false);

            //3. Write out the operation
            fw.write("I have a dream!\n");
            fw.write("you need to have a dream!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. Closing of flow resources
            if(fw != null){

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


    }

Copy operation: (character stream)


    @Test
    public void testFileReaderFileWriter() {
        FileReader fr = null;
        FileWriter fw = null;
        try {
            //1. Create an object of File class to indicate the read in and write out files
            File srcFile = new File("hello.txt");     //Character streams cannot be used to process byte data such as pictures
            File destFile = new File("hello2.txt");

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


            //3. Read and write data
            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();
            }

        }

    }

}

Byte stream:


/**
 * Test the use of FileInputStream and FileOutputStream
 *
 * Conclusion:
 * 1. For text files (. txt,.java,.c,.cpp), use character stream processing
 * 2. For non text files (. jpg,.mp3,.mp4,.avi,.doc,.ppt,...), use byte stream processing
 */
public class FileInputOutputStreamTest {

    //Using byte stream FileInputStream to process text files may cause garbled code.
    @Test
    public void testFileInputStream() {
        FileInputStream fis = null;
        try {
            //1. Documentation
            File file = new File("hello.txt");

            //2. Flow generation
            fis = new FileInputStream(file);

            //3. Read data
            byte[] buffer = new byte[5];
            int len;//Record the number of bytes read each time
            while((len = fis.read(buffer)) != -1){

                String str = new String(buffer,0,len);
                System.out.print(str);

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

            }
        }

    }

    /*
    Copy the picture
     */
    @Test
    public void testFileInputOutputStream()  {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            //
            File srcFile = new File("puppy.jpg");  //Find a picture yourself
            File destFile = new File("Puppy 1.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();
                }

            }
        }

    }

    //For the copy of files under the specified path, we write this copy operation as a method and call it directly
    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]; //Typically, the length of this byte array is 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 whether this method is available
    @Test
    public void testCopyFile(){

        long start = System.currentTimeMillis();

        String srcPath = "C:\\Users\\Administrator\\Desktop\\01-video.avi";
        String destPath = "C:\\Users\\Administrator\\Desktop\\02-video.avi";


//        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));//618 record the time of copying this video. Next time we use the buffer stream, we'll see the change of time.

    }

}

  • When reading a file, you must ensure that the file already exists, otherwise an exception will be reported.
  • Byte stream operation bytes, such as:. mp3,. avi,. rmvb, mp4,. jpg,. doc,. ppt
  • Character stream can only operate on ordinary text files. The most common text files:. txt,. java,. c,. cpp and other language source code. In particular, note that. Doc, Excel and PPT are not text files.

Topics: Java