Java basics-IO stream uses byte stream to read and write files


1. Introduction to IO stream 1. Definition
IO stream refers to a string of flowing strings, which is a channel for sending information in a first-in, first-out manner; through the IO stream, files on the hard disk can be manipulated.
2. Classification
According to the flow direction, the IO stream can be divided into input stream and output stream;
according to the data processing unit, the IO stream can be divided into byte stream and character stream;
the base class of byte input stream is FileInputStream; the
byte output stream The base class is FileOutputStream; the base class of
character input streams is Reader; the base class of
character output streams is Writer.
2. Realize file reading and copying through byte stream The
example realizes copying D://filecopy/oldfile.txt to D://oldfile.txt
(1) Code

import java.io.*;
/**
 * @author ThinkPad
 * @date 2020/5/25 19:16
 */

public class test1 {
    
    
    public  static  void main(String[] args){
    
    
        //字节输入输出流
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
    
    
            fis = new FileInputStream("D://filecopy/oldfile.txt");
            fos = new FileOutputStream("D://oldfile.txt");
            //io读数据的时候,数据存的位置(相当于传输数据的管子)
            byte bs[] = new byte[1024];
            int i = 0;
            //read()方法返回的int类型,是表示数据下一个字节的字节码,如果已经到达流的最后面了,那就返回-1
            while(i!=-1){
    
    
                //read()的内容就写入新的文件                
            fos.write(bs,0,i);
            i= fis.read(bs);
            }
            System.out.println("数据复制完成");
        }
        catch(Exception e){
    
    
            e.printStackTrace();
        }
        finally{
    
    
            try {
    
    
                fos.close();
                fis.close();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

(2) The knowledge point
bs[] is used to read the original file and put it into the storage space of the new file, which can be understood as the water pipe when the water is discharged;
the int type returned by the read() method in FileInputStream represents the data One byte of bytecode, if it has reached the end of the stream, it returns -1.
(3) Execution results
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44801116/article/details/106347605