IO stream principle and stream classification basic introduction to FileInputStream class and FileOutputStream class

IO stream principle and stream classification

How java IO streams work
  1. I/O is the abbreviation of Input stream / Output stream. I/O technology is a very practical technology for processing data transmission. Such as reading and writing files, network communication, etc.
  2. In Java program, the input / output operation of data is carried out in the form of stream
  3. java. Various "stream" classes and interfaces are provided under the IO package to obtain different kinds of data and input or output data through methods
  4. input: read external data [such as data from disk, optical disc and other storage devices] into the program [memory]
  5. Output: output program [memory] data to disk, optical disc and other storage devices
Classification of flow

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly

Binary files such as audio, video and pictures are processed with byte stream

Text files are processed with characters

InputStream OutputStream Reader Writer these four classes are abstract classes

InputStream class inheritance diagram

OutputStream class inheritance diagram

Reader class inheritance diagram

Writer class inheritance diagram

I/O flow system diagram

InputStream byte input stream

The InputStream abstract class is a superclass of all class byte input streams

InputStream class inheritance diagram

Commonly used subclasses of InputStream

FileInputStream: file input stream

BufferedInputStream: buffered byte input stream

ObjectInputStream: object byte input stream

FileInputStream file input stream
Constructor and Description
FileInputStream(File file) creates a FileInputStream by opening the connection with the actual file, which is named by the file object file in the file system.
FileInputStream(FileDescriptor fdObj) creates a FileInputStream by using the file descriptor fdObj, which represents an existing connection in the file system to an actual file.
FileInputStream(String name) creates a FileInputStream by opening a connection to the actual file, which is named by the pathname in the file system.

Common methods:

intread() reads one byte of data from the input stream.
intread(byte[] b) reads up to b.length bytes of data from the input stream, which is a byte array.
intread(byte[] b, int off, int len) reads up to len bytes of data from the input stream, which is a byte array
voidclose() closes the file input stream and frees any system resources associated with the stream
package IO_.fileInputStream;

import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author: Haikang
 * @version: 1.0
 */
public class FileInputStream1 {
    public static void main(String[] args)  {
        String filePath = "e:\\IDEACODE\\javase\\hello.txt";
        FileInputStream fis = null;
        try {
            fis  = new FileInputStream(filePath);
            while (true) {
                int read = fis.read();
                // read returns - 1, indicating that the reading is complete
                if (read == -1){
                    break;
                }
                System.out.print((char) read);// Convert it to char characters
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Be sure to close the convection after use
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @Test
    public void testFileInputStream(){
        String filePath = "e:\\IDEACODE\\javase\\hello.txt";
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(filePath);
            byte[] inputData = new byte[1024*8];
            int len = 0;
            while ((len=fis.read(inputData))!=-1){
                System.out.println(new String(inputData,0,len));// Convert it to string display
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // Be sure to close the convection after use
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

OutputStream file output stream

FileOutputStream file input stream

FileOutputStream class constructor

Constructor and Description
FileOutputStream(File file) creates a File output stream to write to the File represented by the specified File object. No auto append
Fileoutputstream (File, Boolean append) creates a File output stream to write to the File represented by the specified File object. If you need to add content, you need to use this constructor
FileOutputStream(FileDescriptor fdObj) creates a file output stream to write to the specified file descriptor, representing an existing connection to the actual file in the file system.
FileOutputStream(String name) creates a file output stream and writes it to the file with the specified name. Content will not be automatically added
FileOutputStream(String name, boolean append) creates a file output stream and writes the file with the specified name.

Common methods of FileOutputStream class

Modifier and TypeMethod and Description
voidclose() closes the file output stream and frees any system resources associated with the stream.
voidwrite(byte[] b) writes b.length bytes from the specified byte array to the file output stream.
voidwrite(byte[] b, int off, int len) writes len bytes to the file output stream from the specified byte array at offset off.
voidwrite(int b) writes the specified bytes to this file output stream.

Note: if the file does not exist when writing content, it will be created automatically

Case demonstration:

Requirement: please use FileOutputStream stay a.txt File, write“ hello  world",If the file does not exist, it is created

Using the getBytes method in the String class, you can convert a String into a Bytes array

package IO_.fileOUtputStream_;

import org.junit.jupiter.api.Test;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author: Haikang
 * @version: 1.0
 */
public class FileOUtputStream1 {
    public static void main(String[] args) {

    }

    @Test
    public void writeFile(){
        String writeFilePath = "e:\\IDEACODE\\javase\\a.txt";
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(writeFilePath);
            // Char will be automatically converted to int type, and int can also be automatically converted to char
            fos.write('H');// Only one character can be written

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void writeFile2(){
        String writeFilePath = "e:\\IDEACODE\\javase\\a.txt";
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(writeFilePath);
            // Write a string
            String write = "hello world";
            fos.write(write.getBytes());// Write a string with certainty
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        // For the operation of convection, the flow must be closed to release resources
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void writeFile3(){
        String writeFilePath = "e:\\IDEACODE\\javase\\a.txt";
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(writeFilePath,true);// You can append at the end
            String writeContext = "hello world";
            fos.write(writeContext.getBytes(),0,writeContext.length());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // When using streams, be sure to release resources
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Exercise: require programming to complete the copy of pictures and music

Note: when copying large files, you must use circular copy and use the write (byte [], int, int) method

package IO_.fileOUtputStream_;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author: Haikang
 * @version: 1.0
 */
public class FileCopy {
    public static void main(String[] args) {
        String filePath = "e:\\rose.jpg";
        String file = "d:\\rose.jpg";
        FileInputStream  fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(filePath);
            fos = new FileOutputStream(file);
            byte[] dataFile = new byte[1024*8];
            int length = 0;
            while ((length =fis.read(dataFile))!=-1){
               fos.write(dataFile,0,length);// Be sure to use this method, otherwise there will be problems
            }
            System.out.println("Copy complete!!!");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // Be sure to release resources after use
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

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

Keywords: Java Algorithm

Added by mnuzum on Mon, 07 Mar 2022 14:54:55 +0200