Java basics-IO stream to realize file copy and paste through character stream

1. Introduction
Based on the explanation of byte stream, this section mainly demonstrates the reading and writing of character stream. The basics can be found in the following link:
https://blog.csdn.net/qq_44801116/article/details/106347605
2. Examples
(1) Code

import java.io.*;
/**
 * @author ThinkPad
 * @date 2020/5/26 9:24
 */
public class 通过IO字符流实现文件的复制粘贴 {
    
    
    public static void main(String[] args){
    
    
        //字符输入和输出流
        FileReader fr = null;
        FileWriter fw = null;
        //缓冲输入和输出流
        BufferedReader br = null;
        BufferedWriter bw = null;
        try{
    
    
            fr = new FileReader("D://filecopy/oldfile.txt");
            //为提高读写速度,使用字符缓冲流
            br = new BufferedReader(fr);
            fw = new FileWriter("D://newfile.txt");
            bw = new BufferedWriter(fw);
            String line =br.readLine();
            while(line != null){
    
    
                bw.write(line);
                bw.newLine();
                line = br.readLine();
            }
             System.out.println("数据复制完成");
        }
        catch(FileNotFoundException e){
    
    
            e.printStackTrace();
        }
        catch(IOException e){
    
    
            e.printStackTrace();
        }
        finally{
    
    
            try {
    
    
                bw.close();
                fw.close();
                br.close();
                fr.close();
            }
            catch(IOException e){
    
    
                e.printStackTrace();
            }
        }
    }
}

(2) Knowledge points
a. The character stream uses the FileReader and FileWriter base classes;
b. In order to reduce the number of reads and writes to the disk and improve the efficiency of reading and writing, you can use the character buffer stream, using BufferedReader and BufferedWriter;
c. Buffering work Process
step1: Read the data from the disk into the buffer in batches.
Step2: Output the data in the buffer to the target file/application.

(3) Operation results
Insert picture description here

Guess you like

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